1: class ContactForm( forms.Form ):
   2:     topic = forms.ChoiceField( choices=TOPIC_CHOICES)
   3:     message = froms.CharField( widget = froms.Textarea() )
   4:     sender = forms.EmailField( required = False )
   5:  
   6:     def clean_message(self):
   7:         message= self.clean_data.get('message','')
   8:         num_words = len( message.split())
   9:         if num_words < 4:
  10:             raise forms.ValidationError("Not enough words")
  11:         return message

def contact( request ):

if request.method == 'POST'

form = ContactForm( request.POST )

if form.is_valid():

topic = form.clean_data['topic']

sender = from.clean_data['sender'] from django.core.mail import send_mail send_mail( topic , msg, sender , ['administer@example.com'] ) else: form = ContactForm()

可以使用 initial 字符串

form = ContaceForm( initial={'sender':'user@us.com'}) 在意在 Form类中自定义默认值 message = forms.CharField( initial='Replace with your feedback')

 

或者使用Model 的子类

   1: from models import Publisher
   2: from django.newforms import form_for_model
   3:  
   4: PublisherForm = form_for_model(Publisher)
   5:  
   6: def add_publisher(request):
   7:     if request.method = 'POST'
   8:         from = PulisherForm( request.POST)
   9:         if form.is_valid():
  10:             from.save()
  11:             ...
  12:  

from_for_model 一般用来新建model , form_for_instance 用来 Edit