现在,我假设您在运行每个视图时执行与以下相同的操作:
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")