Display value in Charfield for foreign key in django on error
Let's say I've got a model and it has a foreign key to another one.
class ModelA(models.Model):
field = models.CharField(max_length=100)
class ModelB(models.Model):
model_a = models.ForeignKey(ModelA)
Than I've got this form:
class FormB(models.ModelForm):
model_a = forms.CharField(required=True)
def clean(self):
model_a = self.cleaned_data["model_a"]
try:
v = ModelA.objects.get(model_a=model_a)
self.cleaned_data["model_a"] = v
except Exception:
self._errors['model_a'] = ErrorList(["ModelA not found"])
return self.cleaned_data
Now, whenever I enter a char value in FormB, it'll search for it in the ModelA and return the cleaned data.
When I use the form to list the pre-existing instance it shows the ID and not the value.
def my_view(request):
instance = ModelB.objects.get()[0]
form = FormB(instance=instance)
return render_to_response("bla.html", {"form" : form})
Does anybody knows how I could show the value in this CharField when I pass the i开发者_StackOverflow中文版nstance?
Thanks, Nico
I can think of two options:
Make
model_a
field onModelB
hidden witheditable=false
, and add aCharField
toModelB
to store the text the user entered. Then show this field in the form, but use its value to populatemodel_a
.Use an autocomplete field, for example using django-autocomplete. This allows the user to type the name of the object instead of using a
select
widget. (But falls back to aselect
with no JavaScript).
精彩评论