urls.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. from django import forms
  2. from django.conf.urls import url
  3. from django.contrib import messages
  4. from django.contrib.messages.views import SuccessMessageMixin
  5. from django.http import HttpResponse, HttpResponseRedirect
  6. from django.template import engines
  7. from django.template.response import TemplateResponse
  8. from django.urls import reverse
  9. from django.views.decorators.cache import never_cache
  10. from django.views.generic.edit import FormView
  11. TEMPLATE = """{% if messages %}
  12. <ul class="messages">
  13. {% for message in messages %}
  14. <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>
  15. {{ message }}
  16. </li>
  17. {% endfor %}
  18. </ul>
  19. {% endif %}
  20. """
  21. @never_cache
  22. def add(request, message_type):
  23. # don't default to False here, because we want to test that it defaults
  24. # to False if unspecified
  25. fail_silently = request.POST.get('fail_silently', None)
  26. for msg in request.POST.getlist('messages'):
  27. if fail_silently is not None:
  28. getattr(messages, message_type)(request, msg,
  29. fail_silently=fail_silently)
  30. else:
  31. getattr(messages, message_type)(request, msg)
  32. show_url = reverse('show_message')
  33. return HttpResponseRedirect(show_url)
  34. @never_cache
  35. def add_template_response(request, message_type):
  36. for msg in request.POST.getlist('messages'):
  37. getattr(messages, message_type)(request, msg)
  38. show_url = reverse('show_template_response')
  39. return HttpResponseRedirect(show_url)
  40. @never_cache
  41. def show(request):
  42. template = engines['django'].from_string(TEMPLATE)
  43. return HttpResponse(template.render(request=request))
  44. @never_cache
  45. def show_template_response(request):
  46. template = engines['django'].from_string(TEMPLATE)
  47. return TemplateResponse(request, template)
  48. class ContactForm(forms.Form):
  49. name = forms.CharField(required=True)
  50. slug = forms.SlugField(required=True)
  51. class ContactFormViewWithMsg(SuccessMessageMixin, FormView):
  52. form_class = ContactForm
  53. success_url = show
  54. success_message = "%(name)s was created successfully"
  55. urlpatterns = [
  56. url('^add/(debug|info|success|warning|error)/$', add, name='add_message'),
  57. url('^add/msg/$', ContactFormViewWithMsg.as_view(), name='add_success_msg'),
  58. url('^show/$', show, name='show_message'),
  59. url('^template_response/add/(debug|info|success|warning|error)/$',
  60. add_template_response, name='add_template_response'),
  61. url('^template_response/show/$', show_template_response, name='show_template_response'),
  62. ]