user2086641
user2086641

Reputation: 4371

model form validation using django

I am using model form. I trying to do the same but I am not getting the answer. I am not sure whether the form validation method what I have writen was right.

forms.py

class BookForm(ModelForm):
    class Meta:
        model = Book
        fields=['book_id', 'book_name', 'author_name','publisher_name']

    def clean_book_name(self):
        book_name = self.cleaned_data['book_name']
        if book_name is None:
            raise ValidationError('field mandatory')
        return book_name

    def clean_author_name(self):
        author_name=self.cleaned_data['author_name']
        num_words = len(author_name.split())
        if num_words < 4:
            raise forms.ValidationError("Not enough words!")
        return author_name

I am using ModelForm. I am not writing anything in views.py for this validation.

Template

<div align="center">

    <form action="/addbook/" method="POST"> {% csrf_token %}

        <div class="field">
            {{ form.book_name.errors }}
            <label for="id_book_name">Book Name:</label>
            {{ form.book_name }}
        </div>
        <div class="field">
            {{ form.author_name.errors }}
            <label for="id_email">Author name:</label>
            {{ form.author_name }}
        </div>
        <div class="field">
            {{ form.publisher_name.errors }}
            <label for="id_message">Publisher Name:</label>
            {{ form.publisher_name }}
        </div>

Can anyone help me in resolving this? Please provide me an idea or if there are any errors in my code please notify.

Thanks

Upvotes: 0

Views: 78

Answers (1)

catherine
catherine

Reputation: 22808

def clean_book_name(self):
    book_name = self.cleaned_data['book_name']
    if not book_name:
        raise forms.ValidationError('field mandatory')
    return book_name

Upvotes: 1

Related Questions