custom view decorators

Date: May 2nd 2016
Last updated: May 2nd 2016

Decorators can provide a short cut method for adding extra content to a function. Django has some builtin decorators like the login_required decorator. For more information on decorators see oop/decorators pt1, oop/decorators pt2, and oop/decorators pt3.

useful resources

views.py
In this example, only a user (via request) can implement the editfins method if they are also associated with the surfer who added the fins in the first place.

from functools import wraps

def surfer_matches_user(test_func):
    @wraps(test_func)
    def _wrapped_view(request,surfer_id):
        if int(request.user.surfer.id) == int(surfer_id):
            return test_func(request, surfer_id)
        else:
            return redirect('/{}/'.format(request.user.surfer.id))
    return _wrapped_view


@login_required
@surfer_matches_user
def editfins(request, surfer_id, fins_id):
    fins = get_object_or_404(Fin, pk=fins_id)
    form = FinsForm(request.POST or None, instance=fins)
    if form.is_valid():
        form.save()
        return redirect('/{}/'.format(surfer_id))
    return render(request, 'surferprofile/updatefins.html',
            {'fins': fins, 'form': form})

results matching ""

    No results matching ""