开发者

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:

  1. Make model_a field on ModelB hidden with editable=false, and add a CharField to ModelB to store the text the user entered. Then show this field in the form, but use its value to populate model_a.

  2. 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 a select with no JavaScript).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜