1

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:

  1. choose category 'HTML' in the select window
  2. fill 'w3c' in the name field
  3. 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',)
NullPointer
  • 412
  • 7
  • 17

3 Answers3

0

Instead of setting initial like you have here

views = forms.IntegerField(widget=forms.HiddenInput(),initial=0)

Just use this

views = forms.IntegerField(widget=forms.HiddenInput())

and then change this

form = PageForm(request.POST)

to this

form = PageForm(request.POST, initial={"views": "0"})

I am referring to this post.

Community
  • 1
  • 1
Matt Cremeens
  • 4,951
  • 7
  • 38
  • 67
  • Still dose not work, and same with the CharField, but I defined category form in the same manner as page, it works. I'll add category form in the problem statement. – NullPointer May 11 '17 at 15:35
  • Also post your template, please. – Matt Cremeens May 11 '17 at 15:37
  • I upload the code to the github page, and add the links in the last line of the problem statement. Please check, and thanks for your patience. – NullPointer May 11 '17 at 15:52
  • `forms.py` in your git repository isn't matching your code here. In `PageForm` you have `fields = ('title','url','category')`. What happens if you add `views` to that tuple? – Matt Cremeens May 11 '17 at 18:36
  • Yes when I try to paste my Category view here and it occured to me that maybe I shouldn't include hidden fields in the meta description, but after I change that it still didn't work. – NullPointer May 12 '17 at 13:06
0

Just exclude field 'category' in the PageForm and restart server can work.

NullPointer
  • 412
  • 7
  • 17
0

Change your view like this,

def add_page(request): 
    if request.method == 'POST': 
        form = PageForm(request.POST)
        if form.is_valid(): 
            page = form.save(commit=False)
            page.views = 0 
            page.save()
            return redirect('index') 
        else: 
            render(request, 'rango/add_page.html', {'form':'form.errors'}
    else: 
        form = PageForm()
    context_dict = {'form':form}
    return render(request,'rango/add_page.html',context_dict)

You should put commit=False, when saving the form, for adding additional data.

zaidfazil
  • 9,017
  • 2
  • 24
  • 47