Login

Cancel URL Mixin

Author:
halfnibble
Posted:
May 20, 2015
Language:
Python
Version:
1.7
Tags:
template django mixin update create cbv
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

Comments

Please login first before commenting.