Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Django form validation error with incomplete fields but complete instance
- def update_profile(request, username):
- user = Profile.objects.get(user__username=username)
- # update subset of profile, eg value_to_company is set in request.POST
- # but user (or an arbitrary number of other attributes) is not
- profile = ProfileForm(request.POST, instance=user)
- if not profile.is_valid():
- print profile.errors #user is required
- class Profile(models.Model):
- user = models.ForeignKey(auth.models.User)
- value_to_company = models.IntegerField()
- class ValueField(forms.Field):
- def to_python(self, value):
- vals = {'high': 0,
- 'mid': 1}
- return vals[value]
- class ProfileForm(forms.ModelForm):
- value_to_company = ValueField()
- class Meta:
- model = Profile
- # replaces `if not profile.is_valid()` above:
- errors = []
- for field in request.POST.iterkeys():
- if field in profile.fields:
- profile.fields[field].to_python()
- if not profile.fields['field'].clean():
- errors.append #something
- class BaseModelForm(forms.ModelForm):
- """
- Subclass of `forms.ModelForm` which makes sure that the instance values are present in the form
- data, so you don't have to send all old values for the form to actually validate. Django does not
- do this on its own.
- """
- def merge_from_instance(self):
- # Internals
- self.data._mutable = True
- fun = lambda v: v not in self.data.keys()
- for field in filter(fun, self.fields.keys()):
- if field not in self.initial:
- continue
- value = self.initial.get(field)
- if isinstance(self.instance._meta.get_field(field), related.ManyToManyField):
- self.data.setlist(field, value)
- else:
- self.data[field] = value
Add Comment
Please, Sign In to add comment