Reputation: 2727
I have a modelform in which users can enter their bio. I don't want the bio to exceed 10 lines. I'm wondering where and how can I achieve this?
Here is the model:
class UserProfile(models.Model):
username = models.OneToOneField(User)
name = models.CharField(max_length=30)
bio=models.TextField(blank=True)
Update: Thanks to answer by electrometro, I added this validation method to the model:
def enforce_bio(self):
bio = self.cleaned_data['bio']
rows = bio.split('\n')
if len(rows) > 10:
raise forms.ValidationError("bio too long!")
else:
return bio
but it does not work as it should, that is, it allows bios longer than 10 lines. What is wrong here?
Upvotes: 0
Views: 63
Reputation: 8061
You can do this, for example:
def max_ten_lines(value):
rows = value.split('\n')
if len(rows) > 10:
raise ValidationError("bio too long!")
class UserProfile(models.Model):
username = models.OneToOneField(User)
name = models.CharField(max_length=30)
bio = models.TextField(blank=True, validators=[max_ten_lines])
Upvotes: 1
Reputation: 4158
In your validation of your form you could easily split the text by the number the new line character and then just get the length of that list. Then if it is too long you can just send the form back as invalid by raising a ValidationError
on the forms clean method.
The only problem with this is that it doesn't put that logic/validation check on the database. So you would need to do this everywhere the form is used.
For more information take a look at Django form validation here.
Edit:
To split the text into a list it would simply be rows = text.split('\n')
and then to get the length of that list it would be rows_length = len(rows)
. That would tell you how many lines the text is. You would have to do that inside your form validation.
Upvotes: 2