`

Django中的中使用Form的示例

阅读更多

这个主要是练习Form的使用和request接收form数据的示例。

 

form的代码 :

 

from django import forms

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=30);
    email = forms.EmailField(max_length=30);
    phone = forms.CharField(max_length=15);
    
     
    

 

 

 

URL配置 :

 

    (r'add_contact/$','view.add_contact'),
    (r'contact/$','view.contact'),
    
     

 

View代码:

def add_contact(request):
    form = ContactForm()
    return render_to_response("add_contact.html",locals());

def contact(request):
    form = ContactForm(request.POST)
    if(form.is_valid):
        "success"
        return render_to_response("add_contact.html",locals());
    else:
        print "error!!!"
        form = ContactForm()
        return render_to_response("search_form.html",locals());
        
    

 

 

网页代码 :

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <title>Add contact</title>
    </head>
    <body>
        {% if form.errors %}
        <p style="color: red;">
            Please correct the error{{ form.errors|pluralize }} below.
        </p>
        {% endif %}
		
		
        <form method="POST" action="/contact/">
            <table>
                {{form.as_table}}
            </table>
            <input type="submit" value="submit"/>
        </form>
    </body>
</html>

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics