我正在尝试对Django提供的基本泛型View对象进行子类化,这样我就可以完全控制视图的呈现,但仍然使用更干净的基于类的视图方法,而不是映射到函数。
这是我目前的看法:
from django.views.generic.base import View
from django.shortcuts import render
from account.forms import UserForm, UserProfileForm
class RegisterView(View):
def get(request, *args, **kwargs):
user_form = UserForm()
profile_form = UserProfileForm()
return render(request, 'account/register.html', {'user_form': user_form, 'profile_form': profile_form})
def post(request, *args, **kwargs):
pass
当我试图导航到这个视图的URL时,我从Django得到了这个错误:
AttributeError at /account/register/
'RegisterView' object has no attribute 'META'
Request Method: GET
Request URL: http://localhost:8000/account/register/
Django Version: 1.4.3
Exception Type: AttributeError
Exception Value: 'RegisterView' object has no attribute 'META'
Exception Location: C:Python27libsite-packagesdjangocorecontext_processors.py in debug, line 35
Python Executable: C:Python27python.exe
Python Version: 2.7.3
Environment:
Request Method: GET
Request URL: http://localhost:8000/account/register/
Django Version: 1.4.3
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'account')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "C:Python27libsite-packagesdjangocorehandlersbase.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "C:Python27libsite-packagesdjangoviewsgenericbase.py" in view
48. return self.dispatch(request, *args, **kwargs)
File "C:Python27libsite-packagesdjangoviewsgenericbase.py" in dispatch
69. return handler(request, *args, **kwargs)
File "C:projectaccountviews.py" in get
49. return render(request, 'account/register.html', {'user_form': user_form, 'profile_form': profile_form})
File "C:Python27libsite-packagesdjangoshortcuts__init__.py" in render
40. context_instance = RequestContext(request, current_app=current_app)
File "C:Python27libsite-packagesdjangotemplatecontext.py" in __init__
176. self.update(processor(request))
File "C:Python27libsite-packagesdjangocorecontext_processors.py" in debug
35. if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
Exception Type: AttributeError at /account/register/
Exception Value: 'RegisterView' object has no attribute 'META'
在对泛型视图进行子类化时,文档中没有指定任何关于"META属性"的内容,所以我不确定我做错了什么,也不确定这是否是基本泛型视图的允许使用。
我对Python编程和Django有点陌生,所以如果我遗漏了一些明显的东西,请原谅我。
记住这是一个类:您在get
和post
:的定义中错过了self
参数
def get(self, request, *args, **kwargs):