Login

Cancel URL Mixin

Author:
halfnibble
Posted:
May 20, 2015
Language:
Python
Version:
1.7
Score:
0 (after 0 ratings)

CancelMixin

A simple mixin to use with generic.CreateView and generic.UpdateView view form templates to effortlessly implement a "Cancel" button.

This smart mixin will add a URL to your context, {{ cancel_url }}, that can be used as a cancel link in your form template. If no referrer URL is provided, the cancel button will link to default_cancel_url, which can be overridden by view.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class CancelMixin(object):
    default_cancel_url = '/'
    
    def get_context_data(self, arg1=None, **kwargs):
        if arg1 is None:
            context = super(CancelMixin, self).get_context_data(**kwargs)
        else:
            # For WizardViews
            context = super(CancelMixin, self).get_context_data(arg1, **kwargs)

        # First try the referrer URL
        referrer = self.request.META.get('HTTP_REFERER', None) # Known typo
        if referrer is None:
            context['cancel_url'] = self.default_cancel_url
        else:
            context['cancel_url'] = referrer

        return context

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.