ModelForm没有指定模型类

时间:2014-04-06 17:41:55

标签: python django

请帮助解决问题。

我尝试创建用户个人资料页面,用户在注册和登录后到达该页面。加载地址/ userprofile / loaded视图user_profile(请求)。

启动页面显示以下错误消息:

Request Method: GET
Request URL: http://127.0.0.1:8000/userprofile/
Django Version: 1.6.2
Exception Type: ValueError
Exception Value:
ModelForm has no model class specified.
Exception Location: C: \ Python33 \ lib \ site-packages \ django \ forms \ models.py in __ init__, line 308

models.py:

from django.db import models
from django.contrib.auth.models import User


class UserProfile (models.Model):
user = models.OneToOneField (User)
likes_cheese = models.BooleanField (default = True)
favorite_hamster_name = models.CharField (max_length = 50)


User.profile = property (lambda u: UserProfile.objects.get_or_create (user = u) [ 0])

forms.py:

from django import forms
from userprofile.models import UserProfile


class UserProfileForm (forms.ModelForm):

class Meta:
user = UserProfile
fields = ('likes_cheese', 'favorite_hamster_name')

views.py:

from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.template import loader, RequestContext
# from django.core.context_processors import csrf
from userprofile.forms import UserProfileForm
from django.contrib.auth.decorators import login_required


@ login_required
def user_profile (request):
if request.method == 'POST':
form = UserProfileForm (request.POST, instance = request.user.profile)
if form.is_valid ():
form.save ()
return HttpResponseRedirect ('/ accounts / loggedin /')
else:
user = request.user
profile = user.profile
form = UserProfileForm (instance = profile)

args = {}
# args.update (csrf (request))
args ['form'] = form

return render_to_response ('profile.html', args)

创建用户个人资料页面时,我使用了以下tutorials

1 个答案:

答案 0 :(得分:2)

class UserProfileForm (forms.ModelForm):

    class Meta:
        user = UserProfile
...

您的意思是model = UserProfile,而不是user = UserProfile