I need to limit number of tags than can be related to it开发者_运维知识库em. It always should be max 5 tags.
tags = form.cleaned_data['tags']
item.tags = tags
item.save()
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]
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()
精彩评论