[pyar] Django y CSRF

Leonardo Vidarte lvidarte en gmail.com
Mar Jul 19 08:51:38 ART 2011


On Tue, Jul 19, 2011 at 2:00 AM, Marcelo Martinovic
<marcelo.martinovic en gmail.com> wrote:
> Buenas gente:
>
> Hace ya unos días que estoy tratando de implementar en Django 1.3 un
> formulario (estoy probando a ver que onda), es muy simple sin grandes cosas,
> solo tomar 3 datos y tratar de mostrarlos.
> Me leí parte del manual y trate de usar los mismos ejemplos de la pagina
> web, pero nada, me quedo en le mismo punto, contesta esto después de hacer
> submit:
>
>
>
> Forbidden (403)
> CSRF verification failed. Request aborted.
> Help
> Reason given for failure:
>    No CSRF or session cookie.
>
> In general, this can occur when there is a genuine Cross Site Request
> Forgery, or when Django's CSRF mechanism has not been used correctly. For
> POST forms, you need to ensure:
> The view function uses RequestContext for the template, instead of Context.
> In the template, there is a {% csrf_token %} template tag inside each POST
> form that targets an internal URL.
> If you are not using CsrfViewMiddleware, then you must use csrf_protect on
> any views that use the csrf_token template tag, as well as those that accept
> the POST data.
> You're seeing the help section of this page because you have DEBUG = True in
> your Django settings file. Change that to False, and only the initial error
> message will be displayed.
> You can customize this page using the CSRF_FAILURE_VIEW setting.
>
>
>
> Como esto me esta superando y frustrando recurro a alguna alma piadosa que
> me oriente, sea que me diga de donde bajar un ejemplo de como se hace un
> form en Django y así aprendo de implementarlo y modificarlo o que me esta
> faltando agregar al views.py.
> Aclaro.. estoy en ubuntu, es Django 1.3, pruebo con Chrome (firefox tambien
> da el error o sea no creo que sea de navegador), ya agregue {% csrf_token %}
> dentro del form y controle que el MIDDLEWARE_CLASSES tenia
> 'django.middleware.csrf.CsrfViewMiddleware'.
>
> -----------------------------------------------
> views.py
> -----------------------------------------------
> from django.core.context_processors import csrf
> from django.template import RequestContext
> from django.shortcuts import render_to_response
> from models import Noticia
> from models import ContactForm
>
> def contacto(request):
>    if request.method == 'POST': # If the form has been submitted...
>        form = ContactForm(request.POST) # A form bound to the POST data
>        if form.is_valid(): # All validation rules pass
>            # Process the data in form.cleaned_data
>            # ...
>            return HttpResponseRedirect('/thanks/') # Redirect after POST
>    else:
>        form = ContactForm() # An unbound form
>
>    return render_to_response('contacto.html', {
>        'form': form,
>    })
>
> ----------------------------------------------
> contacto.html
> ----------------------------------------------
> <form action="/contacto/" method="post">{% csrf_token %}
> {{ form.as_p }}
> <input type="submit" value="Submit" />
> </form>
>
> Gracias a quien me de una mano. !!!
> Saludos

No había visto el nuevo método (yo usaba el decorador)
pero por lo que entiendo te falta agregar el resultado
de csrf(request) al diccionario que pasás al template.

Fijate este ejemplo sacado de la doc:


from django.core.context_processors import csrf
from django.shortcuts import render_to_response

def my_view(request):
    c = {}
    c.update(csrf(request))
    # ... view code here
    return render_to_response("a_template.html", c)



-- 
⚡ leo



More information about the pyar mailing list