Opened 13 years ago

Last modified 13 years ago

#17137 closed Bug

ModelForm is_valid() accepts options outside choices — at Version 1

Reported by: hayrynen@… Owned by: nobody
Component: Forms Version: 1.3
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Aymeric Augustin)

If form is made using ModelForm and choices of ManyToMany field are limited like this:

# models.py

class Product(models.Model):
   name = models.CharField(max_length=60, verbose_name="Name")
   visibility = models.ManyToManyField(Group, verbose_name="Groups")

# views.py

class ProductForm(forms.ModelForm):
   def __init__(self, group_choices, *args, **kwargs):
       super(ProductForm, self).__init__(*args, **kwargs)
       self.fields['visibility'].choices = group_choices
   class Meta:
       model = Product

@login_required
def products_view(request):
   userprofile = UserProfile.objects.get(user = request.user)
   groups = [ (i.id, i.group) for i in Membership.objects.filter(userprofile=userprofile) ]

   if request.method == "POST":
       form = ProductForm(groups, request.POST)
       if form.is_valid():
           .. do stuff with visibility trusting form.is_valid()

is_valid() allows values for ManyToMany selections outside what is specified in the form as long as there exists corresponding ID in the database. Obviously the submitted form needs to be modified outside standard browser UI.

is_valid() should compare selections against .choices, not against what exists in the database.

Change History (1)

comment:1 by Aymeric Augustin, 13 years ago

Description: modified (diff)

Fixed formatting -- please use wiki syntax and preview.

Note: See TracTickets for help on using tickets.
Back to Top