zoukankan      html  css  js  c++  java
  • Django Form(表单)

    前台用 get 或 post 方法向后台提交一些数据。

    GET方法:

    html示例(保存在templates文件夹中):

    <!DOCTYPE html>
    <html>
    <body>
    <p>请输入两个数字</p>
     
    <form action="/add/" method="get">
        a: <input type="text" name="a"> <br>
        b: <input type="text" name="b"> <br>
         
        <input type="submit" value="提交">
    </form>
     
    </body>
    </html> 

    网页的值传到服务器是通过 <input> 或 <textarea> 标签中的 name 属性来传递的。

    from django.http import HttpResponse
    from django.shortcuts import render
     
    def index(request):
        return render(request, 'index.html')
         
    def add(request):
        a = request.GET['a']
        b = request.GET['b']
        a = int(a)
        b = int(b)
        return HttpResponse(str(a+b)) 

    request.GET 可以看成一个字典,用GET方法传递的值都会保存到其中。可以用request.GET.get('key',None)来取值,没有时不报错。

     

    • 使用 Django 表单(forms)

    示例:

    #forms.py
    from django import forms
    
    class CommentForm(forms.Form):#评论表单
        name = forms.CharField(label='称呼', max_length=16, error_messages={
            'required':'请填写您的称呼',
            'max_length':'称呼太长'
        })
        email = forms.EmailField(label='邮箱', error_messages={
            'required':'请填写您的邮箱',
            'max_length':'邮箱格式不正确'
        })
        content = forms.CharField(label='评论内容', max_length=150, error_messages={
            'required':'请填写您的评论内容',
            'max_length':'评论内容太长'
        })
    #models.py
    class Comment(models.Model):
        blog = models.ForeignKey(Blog)
        name = models.CharField('name',max_length=16)
        email = models.EmailField('email_addres')
        content = models.TextField(max_length=120)
        created = models.DateTimeField(auto_now_add=True)
    #views.py
    def
    get_details(request, p_id): try: blog = Blog.objects.get(id=p_id) except Blog.DoesNotExist: raise Http404 if request.method == 'Get': form = CommentForm() else: form = CommentForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] content = form.cleaned_data['content'] Comment.objects.create(blog=blog, name=name, email=email, content=content) #cleaned_date = form.cleaned_data #cleaned_date['blog'] = blog #Comment.objects.create(**cleaned_date) ctx = { 'blog': blog, 'comments': blog.comment_set.all().order_by('-created'), 'form': form, } return render(request, 'get_details.html', ctx)

    cleaned_data 就是读取表单返回的值,返回类型为字典dict类型。

    email = form.cleaned_data['email']  读取名为'email'的表单提交值,并赋予email变量。

    上述代码中注释的部分是更为简便的方法。

    Form的产出结果是一个字典,可以根据这个Form字典和**直接在数据库创建数据。

    附上处理表单的HTML文件:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Get_Details</title>
    </head>
    <body>
         <header>
         <h3>{{ article.title }}</h3>
         </header>
         <p>{{ article.content }}</p>
         <p>{{ article.created|date:"Y-m-d H:i" }}</p>
        <div class="comments">
            <h3>评论区</h3>
            {% for comment in comments %}
                <p>{{ comment.name }}</p>
                <p>{{ comment.content }}</p>
                <p>{{ comment.created }}</p>
            {% endfor %}
        </div>
        <div class="add_comment">
            <h3>提交评论</h3>
            <form action="{% url 'get_details' blog.id %}" method="post">
                {%  csrf_token %}
                {% for field in form %}
                    <div class="input-field">
                    {{ field.label }}: {{ field }}
                    </div>
                {% endfor %}
                <button type="submit">提交</button>
            </form>
        </div>
    </body>
    </html>

     表格后面还有一个{% csrf_token %}的标签。csrf 全称是 Cross Site Request Forgery。这是Django提供的防止伪装提交请求的功能。POST 方法提交的表格,必须有此标签。

    Django 1.6的官方文档:http://django-chinese-docs-16.readthedocs.io/en/latest/

  • 相关阅读:
    PhpStrom之添加文件夹至左侧目录树
    PhpStorm下载、破解
    ASP.NET 页面执行顺序
    委托的使用 举例猫叫,老鼠逃跑,主人惊醒
    分页显示
    WebForm页面生命周期及asp.net运行机制
    json 对象和json字符串
    说走就走??
    面向多态
    mvc 过滤器篇
  • 原文地址:https://www.cnblogs.com/dear_diary/p/6539038.html
Copyright © 2011-2022 走看看