Reputation: 6540
I need to limit number of tags than can be related to item. It always should be max 5 tags.
tags = form.cleaned_data['tags']
item.tags = tags
item.save()
Upvotes: 1
Views: 119
Reputation: 1195
Assuming tags is a set or list ?!
tags = form.cleaned_data['tags']
if len(tags) < 5:
item.tags = tags
item.save()
else:
print "Oopsy"
Humm you want
tags = form.cleaned_data['tags']
item.tags = tags[:5]
item.save()
Upvotes: 1
Reputation: 6756
I think it is a good idea to do this in clean method of form
class MyForm(forms.Form)
...
def clean_tags(self):
tags= self.cleaned_data['tags']
if len(tags.split(" ")) > 5:
raise forms.ValidationError("you can only add 5 tags")
return tags
EDIT This will be checked when you will call form.is_valid(). When error occurs it is added to form.tags.errors
EDIT
so just
return tags.split(" ")[:5]
Upvotes: 2