Django IntegrityError - 无法弄明白

时间:2014-02-17 02:02:00

标签: python django django-forms django-views

当有一个有效的提交时,即当(我认为)程序进入form.is_valid()分支时,我的porgram会给出IntegrityError。 有没有人知道是什么导致了它?

P.S:我将代码从无形式更改为使用形式,这就是错误开始的时候

我有以下观点

def new_category(request):
if request.method == "POST":
    form = NewCategoryForm(request.POST)
    if form.is_valid():
        cd = form.cleaned_data
        p = Category(name=cd["name"])
        p.save()
        return HttpResponseRedirect(reverse("objects:index"))
    else:
        return render(request,"objects/new_category.html",{"form":form})
else:
    form = NewCategoryForm()
    return render(request,"objects/new_category.html",{"form":form})

和模型

class Category(models.Model):
    name = models.CharField("nome da categoria",max_length=100)

    def __unicode__(self):
        return self.name

    def sorted_events(self):
        return self.event_set.order_by("start")

class Event(models.Model):
    category = models.ForeignKey(Category)
    start = models.DateTimeField("horario", default=0)

和表格

class NewCategoryForm(forms.Form):
    name = forms.CharField(max_length=10,
            error_messages=my_errors)

    def clean_name(self):
        if len(self.cleaned_data["name"]) < 3:
            raise forms.ValidationError("Nome demasiado curto!")

和模板

<!DOCTYPE html>
<html lang="en">

{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'objects/style.css' %}" />


<form action="{% url 'objects:new_category' %}" method="post">
{% csrf_token %}
    <div class="field">
    {% for error in form.name.errors %}
        <p> {{ error }} </p>
    {% endfor %}
    {{ form.name }} 
</div>
<button type="submit">Submit!</button>
</form>

</body>
</html>

编辑1: 我刚刚进行了一些测试,发现了一些奇怪的行为。我总结一个有效的输入,然后执行

print request.POST
print form.is_valid()
print cd   #this one inside the if form.is_valid()

输出是这个

<QueryDict: {u'csrfmiddlewaretoken': [u'ujlYhAFkFd7PuGJMk2aEmvWkDZmg4HlX'], u'name': [u'awdawdd']}>
True
{'name': None}

为什么“name”的值为“None”,如果在request.POST中,“awdawdd”字符串在那里?

编辑2: 更多信息。 奇怪的是,当我尝试在“if form.is_valid()”之前的行中调用form.cleaned_data时,它说:

AttributeError: 'NewCategoryForm' object has no attribute 'cleaned_data'

1 个答案:

答案 0 :(得分:0)

一些返工:

class NewCategoryForm(forms.ModelForm):

    class Meta:
        model = Category
        fields = ['name',]

    def validate_name(name):
        if len(name) < 3:
            raise forms.ValidationError("Nome demasiado curto!")

在视图中:

...
if form.is_valid():
    form.save()  # will save to DB
    return ...
else:
...

或者:

...
if form.is_valid():
    cat = form.save(commit=False)  # won't save to DB
    cat = do_stuff_with_cat
    cat.save()
    # to save another instance, one possibility is:
    cat.pk = None
    cat.save()
    return ...
else:
...