Question

I don't want someone visit my site to comment that only spaces, breaklines on the form. How do I use the command "if" in this case? Thanks for answers !

Was it helpful?

Solution

So I guess what you want is to check if the submitted comment has only spaces or line breaks (i.e. whitespace characters) or is an empty comment and then ignore that comment (or show a message to the user). You can do this using regular expressions:

import re

if re.search('^\s*$', comment_text)
   // empty comment, do something

OTHER TIPS

I'm not sure, if you really want to handle this within the view itself or template. Since some time Django's comment framework let you define moderators where you can implement all the logic you want to detect unwanted comments.

For a nice example on how to use that, take a look at BartTC's django-comments-spamfighter app.

Surely this requires to use Django's comment framework in the first place. If you don't, you could in your validate method of the form strip away all the newlines and whitespaces in general and check, if your comment message is still longer than 0 characters. Strings in Python have a nice little function called strip for those things :-)

I guess you just need to use a form and add a clean method. I've just tried it out in an interactive console:

>>> from django import forms
>>> class CommentForm(forms.Form):
        comment = forms.CharField()
        def clean_comment(self):
           comment = self.cleaned_data['comment']
           comment = comment.strip()
           if len(comment) == 0:
               raise forms.ValidationError('Comment can not be blank')
           else:
            return comment
>>> form = CommentForm(data={'comment': '     '})
>>> form.is_valid()
False
>>> form.errors
{'comment': [u'Comment can not be blank']}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top