ModelForm返回服务器错误(500)

时间:2013-05-29 09:19:49

标签: python django django-forms

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

2 个答案:

答案 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后,我意识到错误来自两个不同的点。

  1. 我的模型中的两个外键字段不能为空(尽管将其模型属性设置为空白= True)。解决后,数据库中出现错误;
  2. 我不确定导致数据库错误的原因,但当我删除数据库,创建一个新数据库并重新运行syncdb时,一切似乎都运行正常。必须与不排队的领域有关。
  3. 再次感谢您的帮助。