【问题标题】:Django, html template, POST submit form not workingDjango,html模板,POST提交表单不起作用
【发布时间】:2019-08-30 21:51:42
【问题描述】:

这个表单中的“提交”按钮,在这个 Django 项目中,似乎没有做任何事情。我无法发现代码或文件中的逻辑错误。

sign.html(这是显示的页面)。单击提交按钮时,它什么也不做,但它应该填充数据库。

{% load static %}
<!DOCTYPE html>
<html>

<head>

  <link rel="stylesheet" href="{% static 'guestbook/styles.css' %}">
</head>
<body>

<h1>Tell the world how you're doing!</h1>
<h2>Sign the guestbook</h2>
<form class="form-signin" method="POST" action="{% url 'sign' %}">
{% csrf_token %}
  Enter your name:<br>
  <!--<input type="text" name="name" placeholder="Your Name here">-->
   {{form.name}}
  <br>
 Enter your comment:<br>
  <!--<textarea name="message" type="Textarea" placeholder="Your comment here" rows="10" cols="30"></textarea>-->
  {{form.comment}}
  <br><br>

  <input type="button" value="Submit">

</form> 


<p>Go to the <a href="{% url 'index' %}"> guestbook </a> itself</p>
</body>
</html>

我怀疑问题出在下面的代码中,或者可能在 views.py 文件中,但由于它没有抛出任何异常,所以我找不到它。

与这个问题相关的是下面的符号函数。

views.py

from django.shortcuts import render
from .models import Comment

from .forms import CommentForm

# Create your views here.

def index(request):
    comments = Comment.objects.order_by('-date_added')
    context ={'comments': comments}
    #name=Name.objects.order_by('-date_added')

    #return render(request,'guestbook/index.html')
    return render(request,'guestbook/index.html', context)


def sign(request):

    if request.method=='POST':
        form = CommentForm(request.POST)

        if form.is_valid():
            new_comment=Comment(name=request.POST['name'],comment=request.POST['comment'])
            new_comment.save()
            return redirect('index')
    else:
        form = CommentForm()

    context={'form' : form}
    return render(request,'guestbook/sign.html',context)

模型文件为要保存到数据库的名称和注释创建模型。

最后,models.py

from django.db import models
from django.utils import timezone

# Create your models here.

class Comment(models.Model):
    name=models.CharField(max_length=20)
    comments=models.TextField()
    date_added=models.DateTimeField(default=timezone.now)
    def __str__(self):
        return self.name    



"""
{% for c in comment %}
{% endfor %}
"""

【问题讨论】:

    标签: django forms templates submit


    【解决方案1】:

    一个表单是通过一个按钮提交的,里面的类型是提交

    <form>
        <!-- button goes here and input fields also -->
    </form>
    

    改变这个

    <input type="button" value="Submit">
    

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

    然后在 views.py 中 更改此new_comment=Comment(name=request.POST['name'],comment=request.POST['comment'])

    new_comment = Comment()
    new_comment.name = request.POST.get("name")
    new_comment.comments = request.POST.get("comment")
    new_comment.save()
    

    【讨论】:

    • 奇怪,现在出现错误:TypeError: Comment() got an unexpected keyword argument 'comment'
    • 这意味着您的表单工作正常。现在问题出在你的代码中`new_comment=Comment(name=request.POST['name'],comment=request.POST['comment'])`
    • 出于安全原因,您应该使用form.cleaned_data['name']form.cleaned_data['comment'],而不是直接使用POST 数据。模型上的字段也是comments,而不是comment,这解释了TypeError
    • 错误告诉您需要做什么:comment 不是Comment 的有效属性。所以你不能做Comment(comment=...)。如果您查看Comment,您会看到您定义了一个字段comments,而不是comment。意思是python期待Comment(comments=...)
    • 如何导入重定向?这是from django.shortcuts import redirect吗?
    【解决方案2】:

    你的post方法应该是这样的:

    def sign(request):
    
     if request.method=='POST':
         form = CommentForm(request.POST)
    
         if form.is_valid():
             new_comment=form.save()
    
             return redirect('index')
     else:
         form = CommentForm()
    
     context={'form' : form}
     return render(request,'guestbook/sign.html',context)
    

    【讨论】:

    • 这种方式非常推荐给初学者。如果您阅读官方教程,您会发现他们是以这种方式教授的。
    • 我同意,但你应该解释一下。
    • 难题的最后一块是弄清楚为什么重定向不起作用
    • @MissComputing 您在 urls.py 上注册了名称“索引”视图?
    • 成功了!非常感谢!
    猜你喜欢
    • 2017-10-03
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    • 1970-01-01
    • 2013-03-16
    • 2016-12-12
    • 2020-08-21
    相关资源
    最近更新 更多