简体   繁体   中英

ModelForm “instance” parameter and foreign key field

I'm trying to initialize an object with in "instance" parameter but it doesn't go into the form. It is a required one so is_valid fails. Can someone please advise, I'm almost sure it's an easy mistake but can't spot it.

FORM:

from django.forms import ModelForm

from tagging.forms import TagField

class BusinessEditForm(ModelForm):
tags = TagField()

class Meta:
    model = Business
    exclude = ('owner', 'pub_date')

Logic in views.py

if businessid:
    b = Business.objects.get(id=businessid)
    category = b.category
    assert(b.owner == request.user) or request.user.is_staff
    #form = forms.BusinessEditForm(request.POST, instance=b)
else:
    assert category.is_public or request.user.is_staff
    b = Business(owner=request.user, category_id=category.id)
    # form = forms.BusinessEditForm(request.POST, instance=b)
    isNew = True

if request.method == "POST":
    form = forms.BusinessEditForm(request.POST, instance=b)

    if form.is_valid():

This last line validates to False.

Any help is welcome.

Thanks, Igor

If you need to pass instance to the form as if it was part of the form data, maybe you can try something like this:

if request.method == "POST":
    form_data = request.POST.copy()
    form_data['instance'] = b
    form = forms.BusinessEditForm(form_data)

If you're excluding required fields in the form, you'll need to set them programatically before calling is_valid() because the form wouldn't create a valid Business object otherwise. This is why is_valid() is returning False .

Without cluttering your views you could write into your forms clean method:

def clean(self):
  self.cleaned_data.update(excluded_field=self.instance.excluded_field)
  return super(YourForm, self).clean()

But you then should also require in your forms __init__ method, that the instance is given and has your excluded fields set.

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