Saturday 3 January 2015

Form in Django

1. Crate a project named csvt07 and an application called blog

Add the application to setttings.py
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
)


2. Setup form procedures

root@10:/home/python/django/csvt07# nano blog/views.py
from django import forms
from django.http import HttpResponse
from django.shortcuts import render_to_response

class UserForm(forms.Form):
    name = forms.CharField()
    sex = forms.CharField()

def register(req):
    if req.method == 'POST':
        form = UserForm(req.POST)
        if form.is_valid():
            print form.cleaned_data
            return HttpResponse('ok')
    else:
        form = UserForm()
    return render_to_response('register.html',{'form':form})


3. create template file

root@10:/home/python/django/csvt07# nano blog/templates/register.html
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-$
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Test Form</title>
</head>
<body>

<form method="post">
{{form}}
<input type="submit" value="ok" />
</form>

</body>
</html>


4. add register url

root@10:/home/python/django/csvt07# nano csvt07/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'csvt07.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),
    url(r'^blog/register','blog.views.register'),
)

5. sync db
root@10:/home/python/django/csvt07# python manage.py syncdb

No comments:

Post a Comment