欢迎加入QQ讨论群258996829
麦子学院 头像
苹果6袋
6
麦子学院

Django表单的三种写法

发布时间:2016-07-12 20:47  回复:0  查看:2836   最后回复:2016-07-12 20:47  

Django是一个卓越的新一代Web框架,是用 Python 编写的一组类库。Django表单是我们学习Django 的必学内容。

 

1、直接在模版中按照xhtmlhtml5 语法写的form表单

<form action="/your-name/" method="post">

    <label for="your_name">Your name: </label>

    <input id="your_name" type="text" name="your_name" value="{{ current_name }}">

    <input type="submit" value="OK">

</form>

这种表单,直接在views中写

 

request.method == "GET"  时,render 模版,在浏览器中显示表单。

request.method == 'POST'时,读取表单中的数据,再和数据库交互。

 

2、继承 Django Form class

 

需要在app下创建一个文件forms.py,如果已经存在就不需要新建。

 

from django import forms

 

class NameForm(forms.Form):

    your_name = forms.CharField(label='Your name', max_length=100)

 

模版文件(name.html)中需要如下这样写。

 

<form action="/your-name/" method="post">

    {% csrf_token %}

    {{ form }}

    <input type="submit" value="Submit" />

</form>

 

views 需要如下写。

 

from django.shortcuts import render

from django.http import HttpResponseRedirect

 

from .forms import NameForm

 

def get_name(request):

    # if this is a POST request we need to process the form data

    if request.method == 'POST':

        # create a form instance and populate it with data from the request:

        form = NameForm(request.POST)

        # check whether it's valid:

        if form.is_valid():

            # process the data in form.cleaned_data as required

            # ...

            # redirect to a new URL:

            return HttpResponseRedirect('/thanks/')

 

    # if a GET (or any other method) we'll create a blank form

    else:

        form = NameForm()

 

    return render(request, 'name.html', {'form': form})

 

3、以models 中定义的类来生成表单(Creating forms from models)

 

>>> from django.forms import ModelForm

>>> from myapp.models import Article

 

# Create the form class.

>>> class ArticleForm(ModelForm):

...     class Meta:

...         model = Article

...         fields = ['pub_date', 'headline', 'content', 'reporter']

 

# Creating a form to add an article.

>>> form = ArticleForm()

 

# Creating a form to change an existing article.

>>> article = Article.objects.get(pk=1)

>>> form = ArticleForm(instance=article)

 

模版中写法参考第二种方法。

 

 

 

原文来自:知乎/黄哥

您还未登录,请先登录

热门帖子

最新帖子