使用django教程探戈(与表单一起玩),错误显示' CategoryForm'对象没有属性' save'请帮助
项目tango_withDjango中有一个app rango p.s.我的程序中的标识是正确的,不像这里......并且使用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')
答案 0 :(得分:2)
CategoryForm
应扩展ModelForm
,而不是Form
。
顺便说一下,class Meta
Form