| 1 | """ |
| 2 | A few bits of helper functions for comment views. |
| 3 | """ |
| 4 | |
| 5 | import textwrap |
| 6 | from urllib.parse import urlencode |
| 7 | |
| 8 | from django.http import HttpResponseRedirect |
| 9 | from django.shortcuts import render, resolve_url |
| 10 | from django.core.exceptions import ObjectDoesNotExist |
| 11 | |
| 12 | from ..compat import url_has_allowed_host_and_scheme |
| 13 | |
| 14 | import django_comments |
| 15 | |
| 16 | |
| 17 | def next_redirect(request, fallback, **get_kwargs): |
| 18 | """ |
| 19 | Handle the "where should I go next?" part of comment views. |
| 20 | |
| 21 | The next value could be a |
| 22 | ``?next=...`` GET arg or the URL of a given view (``fallback``). See |
| 23 | the view modules for examples. |
| 24 | |
| 25 | Returns an ``HttpResponseRedirect``. |
| 26 | """ |
| 27 | next = request.POST.get('next') |
| 28 | if not url_has_allowed_host_and_scheme(url=next, allowed_hosts={request.get_host()}): |
| 29 | next = resolve_url(fallback) |
| 30 | |
| 31 | if get_kwargs: |
| 32 | if '#' in next: |
| 33 | tmp = next.rsplit('#', 1) |
| 34 | next = tmp[0] |
| 35 | anchor = '#' + tmp[1] |
| 36 | else: |
| 37 | anchor = '' |
| 38 | |
| 39 | joiner = ('?' in next) and '&' or '?' |
| 40 | next += joiner + urlencode(get_kwargs) + anchor |
| 41 | return HttpResponseRedirect(next) |
| 42 | |
| 43 | |
| 44 | def confirmation_view(template, doc="Display a confirmation view."): |
| 45 | """ |
| 46 | Confirmation view generator for the "comment was |
| 47 | posted/flagged/deleted/approved" views. |
| 48 | """ |
| 49 | |
| 50 | def confirmed(request): |
| 51 | comment = None |
| 52 | if 'c' in request.GET: |
| 53 | try: |
| 54 | comment = django_comments.get_model().objects.get(pk=request.GET['c']) |
| 55 | except (ObjectDoesNotExist, ValueError): |
| 56 | pass |
| 57 | return render(request, template, {'comment': comment}) |
| 58 | |
| 59 | confirmed.__doc__ = textwrap.dedent("""\ |
| 60 | %s |
| 61 | |
| 62 | Templates: :template:`%s`` |
| 63 | Context: |
| 64 | comment |
| 65 | The posted comment |
| 66 | """ % (doc, template) |
| 67 | ) |
| 68 | return confirmed |