用post方法实现Django表单

来源:互联网 发布:gta5ol 捏脸数据 编辑:程序博客网 时间:2024/06/08 17:17

M

创建评论模型

from django.db import models# Create your models here.class People(models.Model):    name = models.CharField(null=True, blank=True,max_length=200)    job = models.CharField(null=True, blank=True, max_length=200)    def __str__(self):        return self.nameclass Aritcle(models.Model):#新增    headline = models.CharField(null=True, blank=True,max_length=500)#新增    content = models.TextField(null=True, blank=True)#新增    TAG_CHOICES = (        ('tech', 'Tech'),        ('life','Life'),    )    tag = models.CharField(null=True, blank=True, max_length=5, choices=TAG_CHOICES)    def __str__(self):        return self.headlineclass Comment(models.Model):#1    name = models.CharField(null=True, blank=True, max_length=50)#1    comment = models.TextField()#1    def __str__(self):#1        return self.comment#1

迁移合并数据库

python manage.py makemigrationspython manage.py migrate

V

from django.shortcuts import render, HttpResponse, redirectfrom firstapp.models import Aritcle, Comment#2from django.template import Context, Templatefrom firstapp.form import CommentForm# Create your views here.def index(request):    print(request)    print('==='*30)    print(dir(request))    print('==='*30)    print(type(request))    queryset = request.GET.get('tag')    if queryset:        article_list = Aritcle.objects.filter(tag=queryset)    else:        article_list = Aritcle.objects.all()#变量article_list储存Article所有的文章    context = {}#新建字典    context['article_list'] = article_list #字典context中的article_list键(html中通过检索键提取文章内容)对应article_list变量的值    index_page = render(request, 'first_web_2.html', context)    return index_pagedef detail(request):    if request.method == 'GET':        form = CommentForm    #HttpRequest对象request的method属性:表示提交请求使用的HTTP方法。它总是大写的。    if request.method == 'POST':        form = CommentForm(request.POST)        if form.is_valid():            name = form.cleaned_data['name']            comment = form.cleaned_data['comment']            c = Comment(name=name, comment=comment)            c.save()            return redirect(to='detail')    context = {}    comment_list = Comment.objects.all()    context['comment_list'] = comment_list    context['form'] = form    return render(request, 'article_detail.html', context)

HttpRequest对象的属性
path属性
表示提交请求页面完整地址的字符串,不包括域名
如”/music/bands/the_beatles/”。
method属性
表示提交请求使用的HTTP方法。它总是大写的。例如:
if request.method == ‘GET’:
do_something()
elif request.method == ‘POST’:
do_something_else()
GET属性
一个类字典对象,包含所有的HTTP的GET参数的信息。见 QueryDict文档。
POST属性
一个类字典对象,包含所有的HTTP的POST参数的信息。见 QueryDict文档。
通过POST提交的请求有可能包含一个空的 POST字典,也就是说, 一个通过POST方法提交的表单可能不包含数据。因此,不应该使用ifrequest.POST 来判断POST方法的使用,而是使用 ifrequest.method == “POST” (见表中的 method 条目)。
注意: POST 并不 包含文件上传信息。见 FILES。
详细属性链接

U

分配url

"""firstsite URL ConfigurationThe `urlpatterns` list routes URLs to views. For more information please see:    https://docs.djangoproject.com/en/1.11/topics/http/urls/Examples:Function views    1. Add an import:  from my_app import views    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')Class-based views    1. Add an import:  from other_app.views import Home    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')Including another URLconf    1. Import the include() function: from django.conf.urls import url, include    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))"""from django.conf.urls import urlfrom django.contrib import adminfrom firstapp.views import index,detail#从view层引入函数indexurlpatterns = [    url(r'^admin/', admin.site.urls),    url(r'^index', index, name='index'),#url(‘url地址’,函数名,查找方便名)    url(r'^detail', detail, name='detail'),]

T

<!DOCTYPE html>{% load staticfiles %}<html><head>    <meta charset="UTF-8">    <title>Title</title>    <link rel="stylesheet" href="{% static 'css/semantic.css' %}" media="screen" title="no title" charset="utf-8">    <link href="https://fonts.googleapis.com/css?family=0swald|Raleway" rel="stylesheet">    <style type="text/css">        .ui.segment.container{            width:700px;        }        p {            font-family:'Raleway', sans-serif;            font-size:18px;        }        body {            background: url({% static 'images/star_banner.jpg' %});            background-size:cover;            background-repeat:no-repeat;            background-attachment:fixed        }    </style></head><body>    <div class="ui image">        <img src="" alt="" />    </div>    <div class="ui segment padded container">        <h1 class="ui header" style="font-family:'Oswald',sans-serif;font-size: 40px">            Indonesia pointed at Christams        </h1>        <p>            his is how it happens:            The most sensible alternative to a life of unbearable hardship is to take a chance on a rubber dinghy in Indonesia pointed at Christmas Island, which is part of Australia. If a refugee survives, this person is not praised for valor but rather ejected 4,000 miles away to another island. Nauru Regional Processing Center. Processing sounds temporary, and it is, in the same way purgatory is temporary. Asylum seekers have been known to wait five years for intercession in the form of a “refugee status determination,” or RSD.            The agony of waiting is what caused the July 2013 riot. RSDs that were promised were not delivered, and asylum seekers protested. They threw rocks at police and lit fire to buildings. No one was hurt, but the fires caused $60 million in damage. It was probably the most power they’d ever wielded. Nauruan police arrested 153 people around 9:30 p.m. and charged them with rioting. But nothing changed. If anything, the detainees were more forlorn than ever.            Depression was becoming rampant. The older children noticed it, and the little ones, too, though they couldn’t quite understand. Something was wrong. Happiness should be easy at that age. But not in Nauru.            Once, a teacher noticed her student searching the ground for something while waiting for the bus to take him home from school. He was a nice little boy. He’d been given something that morning, a sticker. What a thing. But now he’d lost it, and he anxiously combed the dirt and gravel. “Leave it,” the teacher said. “You can find it later.” The boy said nothing. He just slumped into a pile and sobbed.            When the protests of Sept. 30 amounted to nothing, it was as though a reservoir of grief broke through the last levee, and hopelessness flooded the little camp.            All around were thoughts of suicide. One asylum seeker, Yusuf, told his case manager he thought the mood in the camp was worse than ever. A week earlier, the Australian government had taken the unprecedented step of paying Cambodia (as it paid Nauru) to resettle refugees there. The head of the U.N. refugee agency called it “a worrying departure from international norms” because Australia was essentially paying a poor, unsuitable country to take over its own moral and legal obligations. But Cambodia wanted the money, Australia didn’t want the refugees and to this day the plan is still in place.        </p>    </div>    <div class="ui segment container" style="width:700px;">        <h3 class="ui header" style="font-family: 'Oswald', sans-serif;">Comments</h3><!--标题Comment-->        <div class="ui comments"><!--评论-->            {% for comment in comment_list %}                <div class="comment">                    <div class="avatar">                        <img src="http://semantic-ui.com/images/avatar/small/matt.jpg" alt="" />                    </div>                    <div class="content">                        <a href="#" class="author">{{ comment.name }}</a>                        <div class="metadata">                            <div class="date">2 days ago</div>                        </div>                        <p class="text" style="font-family:'Raleway', sans-serif;">                            {{ comment.comment }}                        </p>                    </div>                </div>            {% endfor %}        </div>        <div class="ui divider"></div><!--分割线评论-->        <form class="ui error tiny form" method="post">            {% if form.errors %}                <div class="ui error message">                    {{ form.errors }}                </div>                {% for field in form %}                    <div class="{{ field.errors|yesno:'error, '}} field"><!--#依次判断表格中的field是否有error-->                    {{ field.label }}                    {{ field }}                    </div>                {% endfor %}            {% else %}                {% for field in form %}                    <div class="field">                        {{ field.label }}                        {{ field }}                    </div>                {% endfor %}            {% endif %}            {% csrf_token %}<!--Django防跨站"{%csrf_token%}"标签-->            <button type="submit" class="ui blue button">Click</button>        </form>    </div></body></html>

F

创建表单

from django import formsfrom django.core.exceptions import ValidationErrordef words_validator(comment):    if len(comment) < 4:        raise ValidationError('Not enough words')def comment_validator(comment):    if 'a' in comment:        raise ValidationError('Do not use that word')class CommentForm(forms.Form):    name = forms.CharField(max_length=50)    comment = forms.CharField(        widget=forms.Textarea(),        error_messages={            'required':'wow,such word'        },        validators=[words_validator,comment_validator]    )

实例化放到Views层中

def detail(request):    form = CommentForm    context = {}    comment_list = Comment.objects.all()    context['comment_list'] = comment_list    context['form'] = form    return render(request, 'article_detail.html', context)

表单放入Template层

<form class="ui error tiny form" method="post"><!--外层form保留,button保留,内部的form.errors和field.label和field增加-->            {% if form.errors %}                <div class="ui error message">                    {{ form.errors }}                </div>                {% for field in form %}                    <div class="{{ field.errors|yesno:'error, '}} field"><!--#依次判断表格中的field是否有error-->                    {{ field.label }}                    {{ field }}                    </div>                {% endfor %}            {% else %}                {% for field in form %}                    <div class="field">                        {{ field.label }}                        {{ field }}                    </div>                {% endfor %}            {% endif %}            {% csrf_token %}<!--Django防跨站"{%csrf_token%}"标签-->            <button type="submit" class="ui blue button">Click</button>        </form>

评论的内容在Template层加上

<div class="ui comments"><!--评论-->            {% for comment in comment_list %}                <div class="comment">                    <div class="avatar">                        <img src="http://semantic-ui.com/images/avatar/small/matt.jpg" alt="" />                    </div>                    <div class="content">                        <a href="#" class="author">{{ comment.name }}</a>                        <div class="metadata">                            <div class="date">2 days ago</div>                        </div>                        <p class="text" style="font-family:'Raleway', sans-serif;">                            {{ comment.comment }}                        </p>                    </div>                </div>            {% endfor %}        </div>
原创粉丝点击