python - ModelForm 没有指定模型类

标签 python django

请帮忙解决问题。

我尝试创建一个用户个人资料页面,用户在注册和登录后即可到达该页面。加载地址/userprofile/加载后查看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

模型.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])

表单.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

最佳答案

class UserProfileForm (forms.ModelForm):

    class Meta:
        user = UserProfile
...

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

关于python - ModelForm 没有指定模型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22897586/

相关文章:

python - 在 Windows 8 (x64) 中安装 PyOpenCL "fatal error: CL/cl.h: No such file or directory"错误

django - 无法对已保存的表单 : object is not JSON serializable 使用 celery 延迟

python - 通过 Nginx 在 Django 中流式传输 mp3 文件

python - 如何找到特定python模块对应的文件?

django - Django SelectMultiple 小部件的动态选择

python - 我是否必须自己刷新 oauth2 access_token,或者

python - 在 Django View 中执行 Python 脚本 [上传 CSV -> 批量地理编码 -> 通过脚本生成的 CSV 显示下载链接]

python - 在python中找到两个列表之间匹配索引的最快方法?

python - Raspi太阳能监控项目,更新mysql数据库

django - 自定义模板标记查询集不返回任何内容