• Django进阶Form篇


    一、django表单系统中,所有的表单类都作为django.forms.Form的之类创建,包括ModelForm

    关于django的表单系统,主要分两种:

    1.基于django.forms.Form:所有表单类的父类

    2.基于django.forms.ModelForm:可以和模型类绑定的Form

    案例:实现添加出版社信息的功能

    二、不使用Django.Form的情况

    add_publisher.html

    <form action="" method="post">
        {% csrf_token %}
        名称:<input type="text" name="name"><br>
        地址:<input type="text" name="address"><br>
        城市:<input type="text" name="city"><br>
        省份:<input type="text" name="state_province"><br>
        国家:<input type="text" name="country"><br>
        网址:<input type="text" name="website"><br>
        名称:<input type="submit" value="提交"><br>
    </form>

    views.py

    from django.http import HttpResponse
    from django.shortcuts import render
    from hello.models import Publisher
    
    
    def add_publisher(request):
        if request.method == 'POST':
            name = request.POST.get("name")
            address = request.POST.get("address")
            city = request.POST.get("city")
            state_province = request.POST.get("state_province")
            country = request.POST.get("country")
            website = request.POST.get("website")
            Publisher.objects.create(
                name=name,
                address=address,
                city=city,
                state_province=state_province,
                country=country,
                website=website,
            )
            return HttpResponse("Add Publisher Succ!")
        else:
            return render(request, 'add_publisher.html', locals())

    三、使用Form的情况

    add_publisher.html

    <form action="{% url 'add_publisher' %}" method="post">
        {% csrf_token %}
        {{ publisher_form.as_p }}
    {#    {{ publisher_form.as_table }}#}
    {#    {{ publisher_form.as_ul }}#}
        <input type="submit" value="提交">
    </form>

    forms.py

    from django import forms
    
    
    class PublisherForm(forms.Form):
        name = forms.CharField(label="名称")
        address = forms.CharField(label="地址")
        city = forms.CharField(label="城市")
        state_province = forms.CharField(label="省份")
        country = forms.CharField(label="国家")
        website = forms.URLField(label="网址")

    views.py

    from django.http import HttpResponse
    from django.shortcuts import render
    from hello.models import Publisher
    from hello.forms import PublisherForm
    
    
    def add_publisher(request):
        if request.method == 'POST':
            publisher_form = PublisherForm(request.POST)
            if publisher_form.is_valid():
                Publisher.objects.create(
                    name=publisher_form.cleaned_data.get("name"),
                    address=publisher_form.cleaned_data.get("address"),
                    city=publisher_form.cleaned_data.get("city"),
                    state_province=publisher_form.cleaned_data.get("state_province"),
                    country=publisher_form.cleaned_data.get("country"),
                    website=publisher_form.cleaned_data.get("website"),
    
                )
                return HttpResponse("Add Publisher Succ!")
        else:
            publisher_form = PublisherForm()
        return render(request, 'add_publisher.html', locals())

    四、使用ModelForm的情况

     add_publisher.html

    <form action="{% url 'add_publisher' %}" method="post">
        {% csrf_token %}
        {{ publisher_form.as_p }}
        <input type="submit" value="提交">
    </form>

    forms.py

    from django import forms
    from hello.models import Publisher
    
    
    class PublisherForm(forms.ModelForm):
        class Meta:
            model = Publisher
            exclude = ('id',)

    views.py

    from django.http import HttpResponse
    from django.shortcuts import render
    from hello.forms import PublisherForm
    
    
    def add_publisher(request):
        if request.method == 'POST':
            publisher_form = PublisherForm(request.POST)
            if publisher_form.is_valid():
                publisher_form.save()
                return HttpResponse("Add Publisher Succ!")
        else:
            publisher_form = PublisherForm()
        return render(request, 'add_publisher.html', locals())

     总结:

    使用Django中的Form可以大大简化代码,常用的表单功能特性都整合到了Form中,而ModelForm可以和Model进行绑定,更进一步简化操作。

    更多详见:https://docs.djangoproject.com/en/1.10/ref/forms/api/

                  https://docs.djangoproject.com/en/1.10/ref/forms/fields/


    ***微信扫一扫,关注“python测试开发圈”,了解更多测试教程!***
  • 相关阅读:
    UVa 11384 Help is needed for Dexter (递归)
    HDU 4355 Party All the Time (三分求极值)
    UVa 11992 Fast Matrix Operations (线段树,区间修改)
    LA 3708 && POJ 3154 Graveyard (思维)
    LA 3942 && UVa 1401 Remember the Word (Trie + DP)
    LA 4329 Ping pong (树状数组)
    HDU 2058 The sum problem (数学+暴力)
    POJ 1458 Common Subsequence (DP+LCS,最长公共子序列)
    代理服务器
    .net垃圾回收
  • 原文地址:https://www.cnblogs.com/guanfuchang/p/6496803.html
Copyright © 2020-2023  润新知