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. 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
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. 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?
EDIT 2: More information. Strangely enough, when i try to call form.cleaned_data right in the line before "if form.is_valid()" it says:
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:
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.