gpt4 book ai didi

python - ModelForm 返回服务器错误 (500)

转载 作者:太空宇宙 更新时间:2023-11-04 10:46:46 25 4
gpt4 key购买 nike

请参阅下面的代码。我正在尝试使用 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>

最佳答案

你的问题在这里:

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

关于python - ModelForm 返回服务器错误 (500),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16810033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com