Dumo
Dumo

Reputation: 13

Raise Error when form has punctuation django

I need a way to raise an error when someone submit something with punctuation in the title. Im a beginner so Im not quite sure how to do so.
Form:

class NeededForm(forms.ModelForm):
    title = forms.CharField(max_length=120)
    likes = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
    body = forms.CharField(min_length=50,widget = forms.Textarea)
    captcha = CaptchaField()

    def clean_title(self):
        data = self.cleaned_data['title']
        return data
    class Meta:
        model = Needed
        fields = ('title', 'body', 'likes')

The view:

def detail(request, needed_title_url):
    context = RequestContext(request)

    needed_name = needed_title_url.replace('_', ' ')
    context_dict = {'needed_name': needed_name}
    try:
        needed = Needed.objects.get(title=needed_name)
        context_dict['needed'] = needed
        print "True!"
    except:
        pass

    return render_to_response('needed.html', context_dict, context)

If the user inputs something like: I like chicken! as a title then I need to show the user an error.

Upvotes: 1

Views: 110

Answers (2)

Burhan Khalid
Burhan Khalid

Reputation: 174622

Try this solution, which makes sure each word in the title contains only letters, numbers, dashes and apostrophes:

import string

def clean_title(self):
    title = self.cleaned_data['title']
    if all(letter not in string.punctuation
             for word in title.split()
             for letter in word
             if letter not in ['-',"'"]):
        return title
    raise forms.ValidationError('Title cannot have punctuation')

Upvotes: 0

Matt
Matt

Reputation: 182

I'm not totally sure to get your question, but it looks like the answer you are looking for may be included in https://docs.djangoproject.com/en/1.6/ref/models/fields/#slugfield

The SlugField is a CharField which can contain only letters, numbers, underscores and hyphens (so it understands max_length,...)

class NeededForm(forms.ModelForm):
    title = forms.SlugField(max_length=120)
    likes = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
    body = forms.CharField(min_length=50,widget = forms.Textarea)
    captcha = CaptchaField()

I you are looking for a more complicated rule checking, have look to the validator page https://docs.djangoproject.com/en/1.6/ref/validators/ and how to use it in a form https://docs.djangoproject.com/en/1.6/ref/forms/validation/#using-validators The example provided is explaining SlugField implementation.

Hope it helps !

Upvotes: 1

Related Questions