Guest User

Untitled

a guest
Aug 20th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. Django form validation error with incomplete fields but complete instance
  2. def update_profile(request, username):
  3. user = Profile.objects.get(user__username=username)
  4.  
  5. # update subset of profile, eg value_to_company is set in request.POST
  6. # but user (or an arbitrary number of other attributes) is not
  7. profile = ProfileForm(request.POST, instance=user)
  8.  
  9. if not profile.is_valid():
  10. print profile.errors #user is required
  11.  
  12. class Profile(models.Model):
  13. user = models.ForeignKey(auth.models.User)
  14. value_to_company = models.IntegerField()
  15.  
  16. class ValueField(forms.Field):
  17. def to_python(self, value):
  18. vals = {'high': 0,
  19. 'mid': 1}
  20. return vals[value]
  21.  
  22. class ProfileForm(forms.ModelForm):
  23. value_to_company = ValueField()
  24.  
  25. class Meta:
  26. model = Profile
  27.  
  28. # replaces `if not profile.is_valid()` above:
  29. errors = []
  30. for field in request.POST.iterkeys():
  31. if field in profile.fields:
  32. profile.fields[field].to_python()
  33. if not profile.fields['field'].clean():
  34. errors.append #something
  35.  
  36. class BaseModelForm(forms.ModelForm):
  37. """
  38. Subclass of `forms.ModelForm` which makes sure that the instance values are present in the form
  39. data, so you don't have to send all old values for the form to actually validate. Django does not
  40. do this on its own.
  41. """
  42.  
  43. def merge_from_instance(self):
  44. # Internals
  45. self.data._mutable = True
  46.  
  47. fun = lambda v: v not in self.data.keys()
  48. for field in filter(fun, self.fields.keys()):
  49. if field not in self.initial:
  50. continue
  51. value = self.initial.get(field)
  52. if isinstance(self.instance._meta.get_field(field), related.ManyToManyField):
  53. self.data.setlist(field, value)
  54. else:
  55. self.data[field] = value
Add Comment
Please, Sign In to add comment