简体   繁体   中英

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 instance?

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM