我建议使用基于类的视图,如果你认为你会一遍又一遍地使用某些东西,例如:表单。您的视图应如下所示:
视图.py:
class BaseView(object):
def __init__(self, request = None , form = None, <#define anything you want here, like model = None or template = None>):
if form:
self.form = form
else:
self.form = FormName
if #AnythingIWant:
self.anythingiwant = anythingiwant
else:
self.anythingiwant = defaultofanythingiwant
def __call__(self, request):
self.request = request
if self.request.method == 'POST':
return self.POST_handler()
else:
return self.GET_handler()
def POST_handler(self):
#method to handle post request
def GET_handler(self):
#method to handle get request
#because u want specific form reusable just add:
# context = {'form' : self.form()}
# then render a template with the context above
def extra_context(self):
return {}
稍后如果您想使用该表单,只需继承BaseView
,例如:
class IndexView(BaseView):
#blahblahblah
如果你想在你的GET_handler()
使用中添加一些东西extra_context
,例如如果你想添加另一个表单:
视图.py:
class ProfileView(BaseView):
def extra_context(self):
form = MyCustomForm()
context = {'custom_form' : form}
return context
至于 urls.py:
url(r'^$', ProfileView(), name='profile_view'),
如果您想更改默认表单,只需像这样覆盖它:
url(r'^$', ProfileView(form = MyCustomCustomForm), name='profile_view'),
现在您可以MyCustomCustomForm
在每个继承的视图中使用BaseView
. 使用基于类的视图的好处是你可以对所有东西都这样做,而不仅仅是表单,也许你想一遍又一遍地使用一些模型