How can I use instance data in form validation in Django?

二次信任 提交于 2019-12-25 04:45:10

问题


I am trying to make sure a list name is unique for a certain user. Here is my view:

    list = List(user=user)
    new_list_form = ListForm(request.POST, instance=list)
    if new_list_form.is_valid():
        new_list_form.save()

And here is the validator that cleans the title (the name of the list):

    def clean_title(self):
        title = self.cleaned_data['title']
        if List.objects.get(user=user, title=title):
            raise forms.ValidationError("List title must be unique.")
        return title

Which doesn't work because 'ListForm' object has no attribute 'user'

How can I access the user variable given by "instance=list" from the clean_title function?


回答1:


The object passed to ModelForm(instance=) is stored in ModelForm().instance. Try

    if List.objects.get(user=self.instance.user, title=title):



回答2:


Or use the unique_together attribute of the Meta class of your model:

class List(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField()

    class Meta:
        unique_together = (("user", "title"),)

Then your form will fail validation if a user attempts to reuse a title.



来源:https://stackoverflow.com/questions/4476603/how-can-i-use-instance-data-in-form-validation-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!