请参阅下面的代码。我正在尝试使用ModelForms将记录添加到数据库,但它不断返回服务器错误 - 似乎是针对.save()操作,但我不太确定。任何帮助我如何解决这个问题都将非常感激。
#view.py
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, render_to_response, get_object_or_404
from django.template import RequestContext
from forms import ContactForm, wallForm
from django.core.mail import send_mail
from home.models import wall
from django.forms import ModelForm
def wallpost(request):
if request.method == 'POST':
new_post = wallForm(request.POST)
if form.is_valid():
f = form.cleaned_data['postContent']
new_post.save()
return HttpResponseRedirect('/home/')
else:
form = wallForm()
return render(request, 'home/wall_post.html', {'form': form,})
#model.py
from django.db import models
class wall(models.Model):
clusterId = models.ForeignKey(cluster)
userId = models.ForeignKey(user)
postContent = models.CharField(max_length=800)
likes = models.IntegerField(default=0)
post_timestamp = models.DateTimeField('date published')
clusterId.blank = True
userId.blank = True
postContent.blank = True
likes.blank = True
post_timestamp.blank = True
#forms.py
from django import forms
from django.forms import ModelForm
from home.models import wall
class wallForm(ModelForm):
class Meta:
model = wall
#template.py
<h1>Posting test</h1>
{% if form.errors %}
<p style="color: red;">
Please correct the error{{ form.errors|pluralize }} below.
</p>
{% endif %}
<form action="" method="post">
<table>
{{ form.as_p }}
</table>
{% csrf_token %}
<input type="submit" value="Submit">
</form>
<b><a href = "/home/">Go back...</a></b>
答案 0 :(得分:4)
你的问题在这里:
def wallpost(request):
if request.method == 'POST':
new_post = wallForm(request.POST)
if form.is_valid():
f = form.cleaned_data['postContent']
new_post.save()
return HttpResponseRedirect('/home/')
else:
form = wallForm()
return render(request, 'home/wall_post.html', {'form': form,})
在这一行if form.is_valid()
中,form
实际上并未定义。您可能需要if new_post.is_valid()
,同样form.cleaned_data
也应该是new_post.cleaned_data
。
此外,由于您未在任何地方使用f = form.cleaned_data['postContent']
,因此不清楚您对此行f
采取的措施。
答案 1 :(得分:0)
感谢您的投入。设置debug = True后,我意识到错误来自两个不同的点。
再次感谢您的帮助。