0

I recently had a situation where the validate_unique method from my model wasn't running. This is because one of the fields involved in the unique test wasn't included in the form. I tried many things in the form and the view before landing on this solution: I first injected the field into the object of the UpdateView, then ran the test in the Form in _post_clean.

models.py 

class Link(ModelBase):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    title = models.CharField(max_length=200,blank=True,null=False)
    url = models.URLField(max_length=400,blank=False,null=False)
    profile = models.ForeignKey('Profile',null=False,blank=False,on_delete=models.CASCADE)

    class Meta:
        unique_together = ('url','profile')

    class Admin:
        pass

forms.py 

class LinkForm(ModelForm):

    def _post_clean(self):
        ''' Be sure that the instance validate_unique test 
            is run including the profile field '''
        super(LinkForm,self)._post_clean()
        try:
            self.instance.validate_unique(exclude=None)
        except ValidationError as e:
            self._update_errors(e)

    class Meta:
        model = Link
        fields = ['title','url']

views.py 

class LinkUpdateView(UpdateView):
    model = Link
    form_class = LinkForm

    def get_form_kwargs(self):
        ''' Add profile to self.object before kwargs are populated '''

        if hasattr(self, 'object') and self.object and self.profile:
                self.object.profile = profile

        kwargs = super(LinkUpdateView, self).get_form_kwargs()

        return kwargs   

Is there a better way to do this that doesn't involve overriding an internal function?

1 Answer 1

1

I had a similar problem a few time, and I solved it this way:

  • I included the field in my form
  • I overrided get_form in my class based view to hide the field to the user, and give it the value I want.

That way, as the field is included, it triggers validation, but the user can not fill it.

It looked like this:

    def get_form(self, form_class=None):
        form = super(MyClass, self).get_form(form_class)
        form.fields['some_field'].initial = some_value
        form.fields['some_field'].widget = forms.HiddenInput()
        return form
1
  • 1
    I thought about doing this, but didn't want to write the validation code for the hidden field. Now that I know how to pass additional kwargs to the form I may revive this idea. Thanks.
    – Dashdrum
    Jan 26, 2018 at 19:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.