How can I use instance data in form validation in Django?
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 = s开发者_开发知识库elf.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?
The object passed to ModelForm(instance=)
is stored in ModelForm().instance
. Try
if List.objects.get(user=self.instance.user, title=title):
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.
精彩评论