Analysis of Django form (2)

A, use in views

Below from my own little demo began recording.

1 #models.py
2 class Other2(models.Model):
3     name = models.CharField(max_length=30)
4     age = models.IntegerField()
5     email = models.EmailField()
6     
7     class META:
8         db_table='Demo'

 1 #coding=utf-8
 2 #forms.py
 3 from django import forms
 4 
 5 class ContactForm(forms.Form):
 6     name = forms.CharField(max_length=30)
 7     age = forms.IntegerField()
 8     email = forms.EmailField(required=False)
 9     #Error class, Once you’ve done that, rows will be given "error" and/or "required" classes, as needed
10     error_css_class='error'
11     required_css_class = 'required'
12 
13 #Custom error list format
14 from django.forms.util import ErrorList
15 class DivErrorList(ErrorList):
16     def __unicode__(self):
17         return self.as_divs()
18     
19     def as_divs(self):
20         if not self:
21             return u''
22         return u'<div class="errorlist">%s</div>' % ''.join([u'<div class="error">%s</div>' %e for e in self])
views.py
def form_test(request):
    """
    ----------------------------------------------
    Function: form test
    DateTime:    2013/9/9
    ----------------------------------------------
    """
    other = Other2.objects.all()
    if request.method == 'POST':
        form = ContactForm(request.POST)    #Post data binding
        if form.is_valid(): #If validated
            #Data cleaning
            name = form.cleaned_data['name']
            age = form.cleaned_data['age']
            email = form.cleaned_data['email']
            
            Other2.objects.create(name=name,age=age,email=email)
            return render_to_response('form/form.html',{'form':form,'other':other})
    else:
        #If the form was not submitted, is an unbound form instance is created
        form = ContactForm(initial={'name':'Hi,here','email':'@'})    #Unbound form
    return render_to_response('form/form.html',{'form':form,'other':other})

html:
<form action='/form/form/' method='post'>{% csrf_token %}
{{form.as_table}}
<input type='submit' value='Submit' class='btn'>
</form>

<hr>
{% for obj in other %}
<p>Name: {{obj.name}}</p>
{% endfor %}

In addition to URLs basically consists of a set of Django form. Then there is a change of sub reset some code.

Two, the custom form template

A learned a lot about custom form display knowledge, here to use in the template.

1,A single display

<form action="/contact/" method="post">
    {{ form.non_field_errors }}
    <div class="field">
        {{ form.name.errors }}
        <label for="id_name">Name:</label>
        {{ form.name}}
    </div>

    <div class="field">
        {% if form.age.errors %}
             {% for err in form.age.errors %}
                <p>{{err|escape}}</p> 
             {% endfor %}
         {% endif %}
        <label for="id_age">Your age:</label>
        {{ form.age}}
    </div>

    <div class="field">
        {{ form.email.errors }}
        <label for="id_email">Your email :</label>
        {{ form.email}}
    </div>
    
    <p><input type="submit" value="Send message" /></p>
</form>

{{The form. field names}} display the corresponding field

{{Form. field name.Errors}} display fields corresponding error

2,Loop output

At the same time can be a circular output all form fields

<form action='/form/form/' method='post'>{% csrf_token %}
{% for field in form %}
    <div class='field'>
        {{field.errors}}<!Error: -->
        {{field.label_tag}}:{{field}}<!Label tag: the form field -->
    </div>
{% endfor %}
<input type='submit' value='Submit' class='btn'>
</form>

In the above loop in {{field}} is an instance of the bound field, it also has the following attributes:

{{field.label}}:Field label, not including the HTML code, such as: Name

{{field.label_tag}}:Field label containing HTML code, such as<label id="id_name">Name:</label>

{{field.html_name}}:Field HTML name, such as: name,age

{{field.help_text}}:Field help text

{{field.errors}}:The field list of errors, can be recycled

3,For the visible and invisible form

You can use the hidden_fields() and visible_fields()

For the form field invisible will not display an error message, the visible in normal display, as follows:

<form action="/contact/" method="post">
    {% for field in form.visible_fields %}
        <div class="fieldWrapper">

            {# Include the hidden fields in the form #}
            {% if forloop.first %}
                {% for hidden in form.hidden_fields %}
                {{ hidden }}
                {% endfor %}
            {% endif %}

            {{ field.errors }}
            {{ field.label_tag }}: {{ field }}
        </div>
    {% endfor %}
    <p><input type="submit" value="Send message" /></p>
</form>

4,Repeated use

If more than one template reuse a form, you can use the'xxx.html '%} {% include (assuming the xxx.html code contained in the form)

<form action="/contact/" method="post">
    {% include "form_snippet.html" %}
    <p><input type="submit" value="Send message" /></p>
</form>

# In form_snippet.html:

{% for field in form %}
    <div class="fieldWrapper">
        {{ field.errors }}
        {{ field.label_tag }}: {{ field }}
    </div>
{% endfor %}

Three, further form class

To reference:

Here is a summary of the notes are as follows:

1,Create a form from a Django model(form model)

This is a trend, combined with Django model and form model close.

#coding=utf-8
from django.db import models
from django.forms import ModelForm  #Import ModelForm

"""Create a form from a Django model(form model)"""
# Comment 
class Comment(models.Model):
    #....

class CommentForm(ModelForm):
    class Meta:
        model = Comment
        #....
#Creating a form to add an comment.
form = CommentForm()
# Creating a form to change an existing comment.
>>> comment = Comment.objects.get(pk=1)
>>> form = CommentForm(instance=comment)

Be careful:

(1),The corresponding field type, field of type Django model field types corresponding to form, here is a list of a few of the key:

Model field Form field
BooleanField BooleanField
CharField   CharField with max_length
 DateField  DateField
 DateTimeField  DateTimeField
 FileField  FileField
 ForeignKey  ModelChoiceField
 IntegerField  IntegerField
 ManyToManyField  ModelMultipleChoiceField
 TextField  CharField with widget=forms.Textarea

(2),The corresponding attribute

If the model field is blank=True, the form class corresponding to the required=False, or required=True

Form field label is set to model field verbose_name  and the first character uppercase.

Form fields corresponding to the help_text models field help_text

If the model field is choices form field widget set Select

Examples are as follows:

#coding=utf-8
from django.db import models
from django import forms
from django.forms import ModelForm  #Import ModelForm

"""Create a form from a Django model(form model)"""
TITLE_CHOICES = (
    ('MR', 'Mr.'),
    ('MRS', 'Mrs.'),
    ('MS', 'Ms.'),
)

class Author(models.Model):
    name = models.CharField(max_length=100)
    title = models.CharField(max_length=3, choices=TITLE_CHOICES)
    birth_date = models.DateField(blank=True, null=True)

    def __unicode__(self):
        return self.name
    
class Book(models.Model):
    name = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)
    
class AuthorForm(ModelForm):
    class Meta:
        model = Author
        
class BookForm(ModelForm):
    class Meta:
        model = Book
        
#The corresponding
class AuthorForm(forms.Form):
    name = forms.CharField(max_length=100)
    title = forms.CharField(max_length=3,widget=forms.Select(choices=TITLE_CHOICES))    #choices
    brith_date = forms.DateField(required=False)
class BookForm(forms.Form):
    name = forms.CharField(max_length=100)
    authors = forms.ModelMultipleChoiceField(queryset=Author.objects.all()) #ManyToManyField

Posted by Joyce at November 26, 2013 - 10:10 PM