views:

78

answers:

3

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 !

+1  A: 

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 :-)

Horst Gutmann
Oh, sorry for the unclear. I just make it for an example. In fact, what I want is how to catch the unwanted characters in the python code. Specifically here is spaces and breaklines.
Tran Tuan Anh
In this case use comment_text.strip to get rid of all the unwanted characters or use a regular expression (as described by tomlog) and embed it within a moderator :-)
Horst Gutmann
A: 

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
tomlog
:) thanks you for this
Tran Tuan Anh
A: 

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']}
gnrfan
wow, really clear. Thanks!
Tran Tuan Anh