[英]Django IntegrityError - can't figure it out
My porgram is giving an IntegrityError when there is a valid submission, that is, when (i think) the program enters the form.is_valid() branch. 当存在有效的提交时,即(我认为)程序进入form.is_valid()分支时,我的porgram给出了IntegrityError。 Does anyone have a clue about what's causing it? 有人知道是什么原因吗?
PS: I changed the code from no form using to form using, and that's when the error started PS:我将代码从无表单使用更改为表单使用,这就是错误开始的时间
I have the following view 我有以下观点
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})
and the models 和模型
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)
and the form 和形式
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!")
and the template 和模板
<!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>
EDIT 1: I just ran some tests and found a somewhat weird behaviour. 编辑1:我只是进行了一些测试,发现有些奇怪的行为。 I sumbit a valid input, and execute 我汇总有效输入,然后执行
print request.POST
print form.is_valid()
print cd #this one inside the if form.is_valid()
the output is this 输出是这个
<QueryDict: {u'csrfmiddlewaretoken': [u'ujlYhAFkFd7PuGJMk2aEmvWkDZmg4HlX'], u'name': [u'awdawdd']}>
True
{'name': None}
Why is the value of "name" being "None", if in the request.POST the "awdawdd" string is there? 如果在request.POST中存在“ awdawdd”字符串,为什么“ name”的值是“ None”?
EDIT 2: More information. 编辑2:更多信息。 Strangely enough, when i try to call form.cleaned_data right in the line before "if form.is_valid()" it says: 奇怪的是,当我尝试在“ if form.is_valid()”之前的行中调用form.cleaned_data时,它说:
AttributeError: 'NewCategoryForm' object has no attribute 'cleaned_data'
A bit of rework: 一点返工:
class NewCategoryForm(forms.ModelForm):
class Meta:
model = Category
fields = ['name',]
def validate_name(name):
if len(name) < 3:
raise forms.ValidationError("Nome demasiado curto!")
And in the View: 并在视图中:
...
if form.is_valid():
form.save() # will save to DB
return ...
else:
...
Or alternatively: 或者:
...
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:
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.