Search code examples
pythondjangoformsdjango-csrf

Django form showing as hidden


I'm doing some work with forms and I believe I did something wrong, my forms arent showing now, I'm doing 4 different pages with a different form on each one.

When I open the page and check the source of the page, the input of my form appears as

<form role="form" method = 'post'><input type='hidden' name='csrfmiddlewaretoken' value='4VlAtXgpblSSq5tkugStVWKWYtZ6rd8A' />



<input type='submit'>
</form>

type = 'hidden' as you can see. Theseare my views:

def add_venta(request):
    ventaForm = VentaForm(request.POST or None)
    if ventaForm.is_valid():
        save_it = ventaForm.save(commit=False)
        save_it.save()
        return redirect("/venta/")
    return render_to_response("venta.html",locals(),context_instace=RequestContext(request))

def add_compra(request):
    rotate_token(request)
    compraForm = CompraForm(request.POST or None)
    if compraForm.is_valid():
        save_it = compraForm.save(commit=False)
        save_it.save()
        return redirect("/compra/")
    return render_to_response("compra.html",locals(),context_instance=RequestContext(request))

def add_accion(request):
    accionForm = AccionForm(request.POST or None)

    if accionForm.is_valid():
        save_it = accionForm.save(commit=False)
        save_it.save()
        return redirect("/accion/")
    return render_to_response("accion.html",locals(),context_instance=RequestContext(request))

def add_banco(request):
    bancoForm = BancoForm(request.POST or None)
    if bancoForm.is_valid():
        save_it= bancoForm.save(commit=False)
        save_it.save()
        return redirect("/banco/")

    return render_to_response("banco.html",locals(), context_instance=RequestContext(request))

the .html files for each view

banco.html

<form role="form" method = 'post'>{% csrf_token %}

    {{ banco.as_p }}

<input type='submit'>

compra.html

<form role="form" method = 'post'>{% csrf_token %}

    {{ compra.as_p }}

<input type='submit'>

venta.html

<form role="form" method = 'post'>{% csrf_token %}

    {{ venta.as_p }}

<input type='submit'>

accion.html

<form role="form" method = 'post'>{% csrf_token %}

    {{ accion.as_p }}

<input type='submit'>

Solution

  • You need to use the same variable name in the template as in the view.

    For example, in the view you have

    ventaForm = VentaForm(request.POST or None)
    

    so in the template you should use

    {{ ventaForm.as_p }}
    

    The hidden input in your question is from the csrf token. This is a security feature, and is meant to be hidden.