使用Django探戈教程探戈(窗体有乐趣),错误显示'CategoryForm'对象没有属性'save'pls help
p.s项目tango_withDjango中有一个应用程序rango。标识在我的程序中是正确的,与这里不同...并且使用ModelForm将显示​​错误
views.py是

 from django.http import HttpResponse
 from django.template import RequestContext
 from django.shortcuts import render_to_response
 from rango.models import Category
 from rango.models import Page
 from rango.forms import CategoryForm
 def add_category(request):
 # Get the context from the request.
 context = RequestContext(request)


# A HTTP POST?
 if request.method == 'POST':
    form = CategoryForm(request.POST)

    # Have we been provided with a valid form?
    if form.is_valid():
        # Save the new category to the database.
        form.save()


        # Now call the index() view.
        # The user will be shown the homepage.
        #return index(request)
    else:
        # The supplied form contained errors - just print them to the terminal.
        print form.errors
else:
    # If the request was not a POST, display the form to enter details.
    form = CategoryForm()

# Bad form (or form details), no form supplied...
# Render the form with error messages (if any).
return render_to_response('rango/add_category.html', {'form': form}, context)




models.py`
from django.db import models
class Category(models.Model):
name=models.CharField(max_length=128,unique=True)
def __unicode__(self):
    return self.name

class Page(models.Model):
category=models.ForeignKey(Category)
title=models.CharField(max_length=128)
url=models.URLField()
views=models.IntegerField(default=0)
def __unicode__(self):
    return self.title




forms.py
from django import forms
from rango.models import Page,Category
class CategoryForm(forms.Form):
name=forms.CharField(max_length=128,help_text="Please enter Category name")
views=forms.IntegerField(widget=forms.HiddenInput(),initial=0)
likes=forms.IntegerField(widget=forms.HiddenInput(),initial=0)
class Meta:
model=Category
class PageForm(forms.ModelForm) :
title=forms.CharField(max_length=128,help_text="Please enter title of the Pages")
url=forms.URLField(max_length=200,help_text="please enter url of the page")
views=forms.IntegerField(widget=forms.HiddenInput(),initial=0)

class Meta :
model=Page
fields=('title','url','views')

最佳答案

CategoryForm应该扩展ModelForm,而不是Form

顺便说一句,class Meta不存在Form

10-08 02:30