I'm following a Django tutorial to build a small site which you can add pages and category in the site, I defined a Page model as below:
class Page(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
title = models.CharField(max_length=128)
url = models.URLField()
views = models.IntegerField(default=0)
def __str__(self):
return self.title
and defined a modelform as below:
class PageForm(forms.ModelForm):
title = forms.CharField(max_length=128, help_text="Please enter the title of this page")
url = forms.URLField(max_length=200, help_text="Please enter the URL of the page")
views = forms.IntegerField(widget=forms.HiddenInput(),initial=0)
category = forms.ModelChoiceField(queryset=Category.objects.all(),help_text="Please choose a category for the page")
class Meta:
model = Page
fields = '__all__'
and views to add_page is:
def add_page(request):
if request.method == 'POST':
form = PageForm(request.POST)
if form.is_valid():
page = form.save(commit=True)
print(page)
page.views = 0
page.save()
return index(request)
else:
print('error')
form.errors
else:
form = PageForm()
context_dict = {'form':form}
return render(request,'rango/add_page.html',context_dict)
But when I run the site and fill the information like this in the field:
- choose category 'HTML' in the select window
- fill 'w3c' in the name field
- fill 'http://www.w3cshools.com' in the url field
and choose to 'create a page' but there's no response after clicking the button nor the data in the form is added into the database, I try to debug using print and found that the data can't pass through the validation which no process of the if block 'form.is_valid()' but I can't understand why and how to da modification.
my category model is defined as:
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
views = models.IntegerField(default=0)
likes = models.IntegerField(default=0)
slug = models.SlugField(unique=True)
def save(self,*args,**kwargs):
self.slug = slugify(self.name)
super(Category, self).save(*args,**kwargs)
def __str__(self):
return self.name
category form:
class CategoryForm(forms.ModelForm):
name = forms.CharField(max_length=128, help_text="Please enter the category name.")
views = forms.IntegerField(widget=forms.HiddenInput(),initial=0)
likes = forms.IntegerField(widget=forms.HiddenInput(),initial=0)
slug = forms.CharField(widget=forms.HiddenInput(),required=False)
class Meta:
model = Category
fields = ('name',)
- views
- This field is required.
[11/May/2017 14:09:41] "POST /rango/add_page/ HTTP/1.1" 200 1404", but I defined the hidden field and it works well with category... – NullPointer May 11 '17 at 14:14