我没有找到任何关于此的明确文档,但我有一个联系表单,我需要在侧边栏中使用多个视图。目前我的代码很脏,因为我在多个视图中重复下面的代码片段来处理表单。有没有办法将Post Request放在可以继承的模板中?
查看
def contact(request):
form_class = ContactForm
if request.method == 'POST':
form = form_class(data=request.POST)
messages.add_message(request, messages.SUCCESS, 'Thank you, we have received your message.')
if form.is_valid():
...
感谢您的帮助。
答案 0 :(得分:1)
现在,我假设您在运行每个视图时执行与以下相同的操作:
def contact(request):
# First you choose the form.
form_class = ContactForm
# Then you want to know if request is POST type
if request.method == 'POST':
# You take the form data from given POST
form = form_class(data=request.POST)
# You add message to messages.
messages.add_message(request, messages.SUCCESS, 'Thank you, we have received your message.')
如果您一遍又一遍地执行相同操作,则可以在任何应用的views.py
文件的开头创建自己的功能,以便将其缩短,并not to repeat yourself一次又一次。
def take_message(request, form, messages, message):
if request.METHOD == "POST":
# I'm reinitializing <form> variable here.
form = form(data=request.POST)
# That <message> variable below must be a string, then you can dynamically pass your message.
messages.add_message(request, messages.SUCCESS, message)
然后在您的视图中使用它:
def contact(request):
take_message(request, ContactForm, messages, "Thanks, we got your message.")
# And the rest here.
但是,我建议您使用class-based views,因为它们可以处理任何请求类型作为方法。所以,我正在改变take_message
方法,如下所示:
def take_message(request, form, messages, message):
# I'm reinitializing <form> variable here.
form = form(data=request.POST)
# That <message> variable below must be a string, then you can dynamically pass your message.
messages.add_message(request, messages.SUCCESS, message)
然后,我的观点如下:
from django.views.generic import TemplateView
# And any other important imports.
# ...
class ContactView(TemplateView):
template_name = "contact.html" # This is your template.
def get(self, request):
# Do things when the method is GET. Like, viewing current messages in a hypothetical admin template.
def delete(self, request):
# Do things when the method is DELETE. Don't forget to use authentication here, so only superuser can delete messages.
def post(self, request):
# Do things when the method is POST.
# I'm assuming anonymous users can send messages, so there's no need for authentication here.
take_message(request, ContactForm, messages, "Thanks you, we got your message.")
# Other things to do.
# urls.py
url(r"^contact/$", ContactView.as_view(), name="contact-page")