2013-03-16 77 views
0

我正在使用模型表單。我試圖做同樣的事情,但我沒有得到答案。我不確定我寫的表單驗證方法是否正確。使用django進行模型表單驗證

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 

我使用的ModelForm。我不在這個驗證的views.py中寫任何東西。

模板

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

誰能幫助我解決這個?請給我一個想法,或者如果我的代碼有任何錯誤,請通知。

由於

回答

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

我應該寫此任何邏輯在views.py – user2086641 2013-03-16 13:32:25

+0

'數據= form.cleaned_data' – catherine 2013-03-16 13:34:18