1

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

2 回答 2

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任何地方使用。

于 2013-05-29T09:23:13.960 回答
0

Thanks for your input. After setting debug = True, I realised that the error was coming from two different points.

  1. Two of my foreign key fields in my model could not be empty (despite setting their model attribute blank = True). Once this was resolved, there was then an error in the database;
  2. I'm not sure what caused the database error, but when I dropped the database, created a new one, and re-ran syncdb, everything seemed to work fine. Must have something to do with fields not lining up.

Thanks again for the help.

于 2013-05-30T01:38:59.140 回答