我正在尝试将数据从我的django模型表单发布到我的数据库,但我没有运气。我可以从管理员创建并在页面上显示,但似乎无法正确传递我的信息。该评论与学校的外键相关联,我知道这有效。这就是我的模型,视图和HTML的内容。
models.py
from django.forms import ModelForm
class Comment(models.Model):
school = models.ForeignKey(Schools)
created = models.DateTimeField(auto_now_add=True)
author = models.CharField(max_length=60)
body = models.TextField()
class CommentForm(ModelForm):
class Meta:
model = Comment
fields = ['author', 'body', 'school']
views.py
EDITED
我还添加了评论对象create,就像尝试另一件事一样。
from my_app.models import Comment, CommentForm
if request.method == 'POST':
form = CommentForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
author = form.cleaned_data['author']
body = form.cleaned_data['body']
school = form.cleaned_data['school']
form.save()
content = Comment.objects.create(school = school, author = author, body = body)
我在这个视图上尝试了很多变化,但还没有运气。
HTML
<form action="/" method="POST">{% csrf_token %}
<p>{{ form.body }}</p>
<div id="submit"><input type="submit" value="Submit"></div>
</form>
答案 0 :(得分:0)
一个。您必须指定{{form.as_p}}
,{{form.as_table}}
或仅{{form}}
而不是{{form.body}}
。查看文档以获取更多详细信息:https://docs.djangoproject.com/en/dev/topics/forms/
B中。 cleaned_data
需要Comment
类的属性。因此,使用body = form.cleaned_data['comment']
body = form.cleaned_data['body']
℃。和Django一起玩。
修改强>
将if request.method == 'POST':
移到新方法中,即register_comment
:
def register_comment:
if request.method == 'POST':
form = CommentForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
author = form.cleaned_data['author']
body = form.cleaned_data['body']
school = form.cleaned_data['school']
form.save()
修改urls.py
:
urlpatters = patterns('',
# Some others views here
url(r'^new-comment/$', 'app_name.views.register_comment', name="new_comment"),
# Maybe Some others views here
)
打开网络浏览器,然后转到:http://127.0.0.1:8000/new-comment/