Article directory
The main role of form is:
1. Form framework generation in html, 2. Validation data
https://www.cnblogs.com/zongfa/p/7709639.html
1. Create some data types in the model
class Users(models.Model): uname = models.CharField(max_length=30,unique=True,verbose_name="User name") upet = models.CharField(max_length=30,verbose_name="Nickname?") upawd = models.CharField(max_length=30,verbose_name="Password") email = models.EmailField(verbose_name="E-mail") url = models.URLField(verbose_name="Website")
2. Create new forms.py in model.py directory
There are two ways of writing:
(1)Define the form model from django import forms class UserForm(forms.Form): uname = forms.CharField(max_length=100 ,label='User name') email = forms.EmailField(label='E-mail') upet = forms.CharField(max_length=30,required=False,label='Nickname?') upawd = forms.CharField(label='Password',widget=forms.Textarea) url = forms.URLField(required=False ,label='Website') (2)inherit model from django.forms import ModelForm from myblog.users.models import Users class UsersForm(ModelForm): class Meta: model = Users fields = ('uname','upet', 'upawd','email','url')
3. Form validation in view view
def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): username=form.cleaned_data['uname'] usernick=form.cleaned_data['upet'] pawd1=form.cleaned_data['upawd'] email=form.cleaned_data['email'] weburl=form.cleaned_data['url'] Users(uname=username,upet=usernick,upawd=pawd1, email=email,url=weburl).save() return HttpResponseRedirect('/index/') else:
4. On the html page, the code is very simple, which django does well.
<form action="/contact/" method="post"> <table class="form-table"> <!--{{ form.as_ul }}--> # This is the first way to write a form in <ul>. <!-- {{ form.as_p }}--> # This is the second way of writing, displaying the form in <p>. <!--{{ form.as_table }}--> # This is the third way to write a form in <table>. {% for field in form %} # This is the fourth way to write a form in circular form {{ field.label_tag }}:{{ field }} {{ field.errors }} {% endfor %} </table> <p class="submit"><input type="submit" name="submit" id="submit" class="button-primary" value="Registration information" /></p> </form>