Opened 13 years ago
Last modified 13 years ago
#17137 closed Bug
ModelForm is_valid() accepts options outside choices — at Initial Version
Reported by: | 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
If form is made using ModelForm and choices of ManyToMany field are limited like this:
-- snip
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.fieldsvisibility.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()
-- snip
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.