Debian Codegraph @

tests/messages_tests/urls.py

raw
1 from django import forms
2 from django.contrib import messages
3 from django.contrib.messages.views import SuccessMessageMixin
4 from django.http import HttpResponse, HttpResponseRedirect
5 from django.template import engines
6 from django.template.response import TemplateResponse
7 from django.urls import path, re_path, reverse
8 from django.views.decorators.cache import never_cache
9 from django.views.generic.edit import DeleteView, FormView
10
11 from .models import SomeObject
12
13 TEMPLATE = """{% if messages %}
14 <ul class="messages">
15 {% for message in messages %}
16 <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>
17 {{ message }}
18 </li>
19 {% endfor %}
20 </ul>
21 {% endif %}
22 """
23
24
25 @never_cache
26 def add(request, message_type):
27 # Don't default to False here to test that it defaults to False if
28 # unspecified.
29 fail_silently = request.POST.get("fail_silently", None)
30 for msg in request.POST.getlist("messages"):
31 if fail_silently is not None:
32 getattr(messages, message_type)(request, msg, fail_silently=fail_silently)
33 else:
34 getattr(messages, message_type)(request, msg)
35 return HttpResponseRedirect(reverse("show_message"))
36
37
38 @never_cache
39 def add_template_response(request, message_type):
40 for msg in request.POST.getlist("messages"):
41 getattr(messages, message_type)(request, msg)
42 return HttpResponseRedirect(reverse("show_template_response"))
43
44
45 @never_cache
46 def show(request):
47 template = engines["django"].from_string(TEMPLATE)
48 return HttpResponse(template.render(request=request))
49
50
51 @never_cache
52 def show_template_response(request):
53 template = engines["django"].from_string(TEMPLATE)
54 return TemplateResponse(request, template)
55
56
57 class ContactForm(forms.Form):
58 name = forms.CharField(required=True)
59 slug = forms.SlugField(required=True)
60
61
62 class ContactFormViewWithMsg(SuccessMessageMixin, FormView):
63 form_class = ContactForm
64 success_url = show
65 success_message = "%(name)s was created successfully"
66
67
68 class DeleteFormViewWithMsg(SuccessMessageMixin, DeleteView):
69 model = SomeObject
70 success_url = "/show/"
71 success_message = "Object was deleted successfully"
72
73
74 urlpatterns = [
75 re_path("^add/(debug|info|success|warning|error)/$", add, name="add_message"),
76 path("add/msg/", ContactFormViewWithMsg.as_view(), name="add_success_msg"),
77 path(
78 "delete/msg/<int:pk>",
79 DeleteFormViewWithMsg.as_view(),
80 name="success_msg_on_delete",
81 ),
82 path("show/", show, name="show_message"),
83 re_path(
84 "^template_response/add/(debug|info|success|warning|error)/$",
85 add_template_response,
86 name="add_template_response",
87 ),
88 path(
89 "template_response/show/", show_template_response, name="show_template_response"
90 ),
91 ]