2014-12-26

Published on 2014-12-26


Django

Forms

Forms in Django could be used for validations. Besides, forms are also useful to generate html scripts for the corresponding elements in them. Forms are always defined as

from django import forms

class TextForm(forms.Form):
    inputTitle = forms.CharField()
    inputContent = forms.CharField()

    def clean_inputTitle(self):
        pattern = re.compile(u'^[a-zA-Z0-9\s\u4e00-\u9fa5]+$')
        pattern_blank = re.compile(u'^\s+$')
        inputTitle = self.cleaned_data['inputTitle']
        l = len(inputTitle)
        if l >= 1 and l <= 16 and pattern.match(inputTitle) and not pattern_blank.match(inputTitle):
            return inputTitle
        raise forms.ValidationError(_('inputTitle_err'))

    def clean_inputContent(self):
        pattern = re.compile(u'^[()!¥?。,《》{}【】“”·、:;‘’……\s\x21-\x7e\u4e00-\u9fa5]+$')
        pattern_blank = re.compile(u'^\s+$')
        inputContent = self.cleaned_data['inputContent']
        l = len(inputContent)
        if l >= 1 and l <= 1000 and pattern.match(inputContent) and not pattern_blank.match(inputContent):
            return inputContent
        raise forms.ValidationError(_('inputContent_err'))

The methods prefixed with clean_ are called when need validation. If there exist errors in the attributes, the method Form.is_valid() will return false, and information about wrong attributes could be retrieved by Form.errors.

The field types in django.forms.Form is here.

Views

In views, there are methods defined to respond to http requests. To do this, you should import some packages.

# render a template to response
from django.shortcuts import render_to_response
# useful for prevention of csrf attacks
from django.template import RequestContext
from django.views.decorators.csrf import ensure_csrf_cookie
# class about other types of http response
from django.http import HttpResponse, HttpResponseRedirect

# corresponding forms and models
from app.forms import SomeForm
from app.models import SomeModel

@ensure_csrf_cookie
def add(request):
    if request.method != 'POST':
        return render_to_response('err.html', {'err': 'should be POST method'})
    form = SomeForm(request.POST)
    if not form.is_valid():
        return render_to_response('err.html', {'err': form.errors.keys()})
    data1 = form.cleaned_data['data1']
    data2 = form.cleaned_data['data2']
    model = SomeModel(attr1 = data1, attr2 = data2)
    model.save()
    return render_to_response('success.html')

The first argument of render_to_response method is a template in Django.

Url Conf

A general example of url configurations is as following.

from django.conf.urls import patterns, include, url

from app import views

urlpatterns = patterns('',
        url(r'^$', views.index),
        url(r'^add/$', views.add),
)

The first argument of patterns is not a url, and it has other functions.

You can include urls from other apps into the project's url configuration file.

from django.conf.urls import patterns, include, url

urlpatterns = patterns('',
        url(r'^app/$', include('app.urls')),
)

In Django, the url configurations support regex expressions, even support arguments. For detail see here.