django - Django,html模板,POST提交表单不起作用
问题描述
在这个 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 文件中,但由于它没有抛出任何异常,所以我找不到它。
下面的符号函数与这个问题相关。
视图.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 %}
"""
解决方案
表单由一个按钮提交,该按钮的类型是内部提交
<form>
<!-- button goes here and input fields also -->
</form>
改变这个
<input type="button" value="Submit">
至
<input type="submit" value="Submit">
然后在views.pynew_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()
推荐阅读
- javascript - history.push 使用 react-router-dom
- spring-webflux - Flux(WebClient)并行调用,然后对收集的列表进行后处理
- php - Laravel - 如何根据选择的单选按钮有条件地显示输入选择框?
- java - 未找到 OnSwipeTouchListener
- mysql - mysql 如果需要,从第 x 行开始选择 n 行循环到表的开头
- python - 保存另一个对象后自动创建对象
- java - 如何在vaadin 8的checkboxGroup中为一个特定的复选框设置css样式
- reactjs - 在 react-bootstrap 和 react-table install 时卡在 npm fund 和 npm audit 的循环中
- python - 安装 Pygame(3.9) 安装时出错 (Win10)
- react-native - Invariant Violation:ListView 已从 React Native 中删除。有关更多信息,请参阅 fb.me/nolistview 或使用 `deprecated`