一分钟学会Django的表单


#forms.py  
 
from django import forms 
 
class ContactForm(forms.Form): 
    subject = forms.CharField() 
    email = forms.EmailField(required=False, label='Your e-mail address') #define label 
    message = forms.CharField(widget=forms.Textarea ) #define output format   
     
    #define custom check method, nameing rule clean_attname(), executed after default clean(),e.g, is_valid() method.  
    #we can set cleand_data to the python value we want, so the value is better returned or we will lost the value.  
     
    def clean_message(self):          
        message = self.cleaned_data['message']         
        num_words = len(message.split())         
        if num_words < 4:             
            raise forms.ValidationError("Not enough words!")         
        return message 
 
[python] view plaincopy
# views.py 
 
from django.shortcuts import render_to_response 
from mysite.contact.forms import ContactForm 
 
def contact(request): 
    if request.method == 'POST': 
        form = ContactForm(request.POST) 
        if form.is_valid():   #if valid, then cleaned_data attr is gen. 
            cd = form.cleaned_data 
            send_mail( 
                cd['subject'], 
                cd['message'], 
                cd.get('email', 'noreply@example.com'), 
                ['siteowner@example.com'], 
            ) 
            return HttpResponseRedirect('/contact/thanks/') 
    else: 
        form = ContactForm()         #or add an initial value           
        form = ContactForm(initial={'subject': 'I love your site!'}) 
    return render_to_response('contact_form.html', {'form': form}) 
 
 
# contact_form.html 
 
<html>  
    <head>     
        <title>Contact us</title>     
        <style type="text/css">      
            ul.errorlist {         
                margin: 0;        
                padding: 0;}     
            .errorlist li {        
                background-color: red;         
                color: white;         
                display: block;         
                font-size: 10px;         
                margin: 0 0 3px;        
                padding: 4px 5px;}    
        </style> 
    </head> 
    <body>     
        <h1>Contact us</h1>      
        {% if form.errors %}         
            <p style="color: red;">             
            Please correct the error{{ form.errors|pluralize }} below.         
            </p>     
        {% endif %}      
         
        <form action="" method="post">        
            <div class="field"> #define you own style             
                {{ form.subject.errors }}             
                <label for="id_subject">Subject:</label>             
                {{ form.subject }}         
            </div>         
            <div class="field">             
                {{ form.email.errors }}             
                <label for="id_email">Your e-mail address:</label>             
                {{ form.email }}        
            </div>        
            <div class="field">             
                {{ form.message.errors }}             
                <label for="id_message">Message:</label>             
                {{ form.message }}         
            </div>         
            <input type="submit" value="Submit">     
        </form>     
         
        <!--{{ form.message.errors }} 会在<ul class="errorlist"> 里面显示,如果字段是合法的,或者form没有被绑定,就显示一个空字符串。-->  
        <!-- 我们还可以把form.message.errors 当作一个布尔值或者当它是list在上面做迭代, 例如:--> 
         
        <div class="field{% if form.message.errors %} errors{% endif %}">     
            {% if form.message.errors %}         
            <ul>         
                {% for error in form.message.errors %}             
                <li><strong>{{ error }}</strong></li>         
                {% endfor %}         
            </ul>     
            {% endif %}     
            <label for="id_message">Message:</label>     
            {{ form.message }} 
        </div> 
         
        <!--在校验失败的情况下, www.2cto.com这段代码会在包含错误字段的div的class属性中增加一个”errors”,在一个有序列表中显示错误信息。--> 
    </body> 
</html>   


摘自 ZhangIt的专栏

相关内容

    暂无相关文章

评论关闭