Реализация страницы подтверждения действия

Давно ничего в блог не писал. Дабы совсем уж не партизаниться решил описать трюк, который недавно придумал. Мне хотелось довольно безболезненно осуществлять показ страницы подтверждения действия для любого view. Например, для удаления какой-либо сущности.

Итоговое решение свелось к тому, что я пишу внутри view следующий код:


check_confirmation(request, 'Вы действительно хотите удалить сообщение "%s" % foo)

check_confirmation(request, ‘Вы действительно хотите удалить сообщение “%s” % foo)

где foo - это то, что я хочу удалить.
Теперь, если пользователь ещё ничего не подтверждал, то при попытке зайти во view удаления ему покажется другой view с формой подтверджения. В общем, смотрите код - там всё понятно.

Пример view:


@render_to('news/delete.html')
def delete(request, news_id):
news = News.objects.get(pk=news_id)
check_confirmation(request, 'Вы действительно хотите удалить новость "%s"' % news)
news.delete()
raise RedirectException(reverse('news.views.manage'), notice_message='Новость удалена')
return {
'news': news,
'form': form}

@render_to(‘news/delete.html’)
def delete(request, news_id):
news = News.objects.get(pk=news_id)
check_confirmation(request, ‘Вы действительно хотите удалить новость “%s”’ % news)
news.delete()
raise RedirectException(reverse(‘news.views.manage’), notice_message=’Новость удалена’)
return {
‘news’: news,
‘form’: form}


А вот файл, со всей фунциональностью. В нём, как вы видите, есть middleware, который, как вы понимаете, надо прописать в settings.py


from django.shortcuts import render_to_response
from django.template import RequestContext

def check_confirmation(request, message):
if '_confirm' in request.POST or '_confirm' in request.GET:
return
else:
raise ConfirmationException(message, request.path)

class ConfirmationException(Exception):
def __init__(self, message, path, *args, **kwargs):
self.message = message
self.path = path
Exception.__init__(self, *args, **kwargs)

def confirmation_view(request, message, path):
output = {
'message': message,
'path': path}
return render_to_response('site/confirmation.html', output,
context_instance=RequestContext(request))

class ConfirmationMiddleware(object):
def process_exception(self, request, exception):
if isinstance(exception, ConfirmationException):
return confirmation_view(request, exception.message, exception.path)
return None

from django.shortcuts import render_to_response
from django.template import RequestContext

def check_confirmation(request, message):
if ‘_confirm’ in request.POST or ‘_confirm’ in request.GET:
return
else:
raise ConfirmationException(message, request.path)

class ConfirmationException(Exception):
def __init__(self, message, path, *args, **kwargs):
self.message = message
self.path = path
Exception.__init__(self, *args, **kwargs)

def confirmation_view(request, message, path):
output = {
‘message’: message,
‘path’: path}
return render_to_response(‘site/confirmation.html’, output,
context_instance=RequestContext(request))

class ConfirmationMiddleware(object):
def process_exception(self, request, exception):
if isinstance(exception, ConfirmationException):
return confirmation_view(request, exception.message, exception.path)
return None


UPD: Забыл показать пример шаблона view подтверждения:


{% extends 'base.html' %}

{% block content %}
<strong>{{ message }}</strong>
<form method="get" action="{{ path }}">
<input type="submit" name="_confirm" value="Да"/>
</form>
{% endblock %}

{% extends ‘base.html’ %}

{% block content %}
<strong>{{ message }}</strong>
<form method=”get” action=”{{ path }}”>
<input type=”submit” name=”_confirm” value=”Да”/>
</form>
{% endblock %}
Add post to:   Google Slashdot Yahoo Digg Technorati Delicious Bobrdobr.ru Newsland.ru Smi2.ru Rumarkz.ru Vaau.ru Memori.ru Rucity.com Moemesto.ru News2.ru Mister-Wong.ru Yandex.ru Myscoop.ru 100zakladok.ru
Make comment

Comments

No comments for this post

Required. 30 chars of fewer.

Required.

captcha image Please, enter symbols, which you see on the image