简体   繁体   中英

Forbidden (403) CSRF verification failed. Request aborted. Django

I have this error when loading the template the model of the form, and enter the amount in the The text sends me to the page Help Reason given for failure: The CSRF symbol is missing or incorrect. From Django, help pls!

views.py:

def ListAll(request, id_especialidad):
especialidad = Especialidad.objects.get(id=id_especialidad)
if request.method == 'GET':
  user = request.user
  if user.is_superuser:
      pedido = Pedido.objects.filter(especialidad=especialidad)
      template  = 'admindata.html'
      return render_to_response(template,locals())
  else:
    if request.method == 'POST':
      form = PedidoEditForm(instance=especialidad)
    else:
      form = PedidoEditForm(request.POST, instance=especialidad)
      if form.is_valid():
          form.save()
          pedido = Pedido.objects.filter(especialidad=especialidad)
  return render_to_response('index2.html',locals(), {'form':form})

template html:

   {% if especialidad.estadistica == "0" %}
   <section id="contenido">
  <div class="container" style="margin:50px auto width="100%"">
     <form id="myform" method="POST">
        {% csrf_token %}
        {{form.as_p}}
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        &nbsp;
        <input type="submit" class= "btn btn-success" value="Guardar">
     {% else %}
     <table id="example" class="table table-border table-striped table-hover">
        <thead>
            <tr> 
                <td>Servicio</td>
                <td>Cod experto</td>
                <td>Nombre</td>
                <td>Cantidad</td>
                <td>Ingresar</td>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <td>Servicio</td>
                <td>Cod experto</td>
                <td>Nombre</td>
                <td>Cantidad</td>
                <td></td>
            </tr>
        </tfoot>
        <tbody>
    {% if pedido  %}
    {% for ped in pedido  %}
            <tr>
                <td>{{ ped.especialidad.nombre }}</td>
                <td>{{ ped.articulo.cod_experto }}</td>
                <td>{{ ped.articulo.nombre }}</td>
                <td>{{ ped.cantidad }}</td>
                <td><a href="{% url "usuario:cant_ingresar" ped.id especialidad.id  %}" method='GET' type="submit" class="btn btn-primary pull-right" value="editar" onclick="document.location.reload();"/>Ingresar</a></td>

            </tr>
    {% endfor %}
    {% endif %}
       </tbody>
       </table>
       </form>

</div>
</section>
</div>    

{% endif %}

model form:

from django import forms
from django.forms import ModelForm
from .models import Pedido, Especialidad


class PedidoEditForm(forms.ModelForm):
    cantidad       = forms.IntegerField(label='Cantidad:',     widget=forms.TextInput(attrs={'size':'10'}))

class Meta:
    model = Pedido


    fields = [

    'cantidad',

    ]  

class EstadisticaForm(forms.ModelForm):
estadistica    = forms.IntegerField(label='Estadistica Menusal:', widget=forms.TextInput(attrs={'placeholder':'Ingrese numero pacientes'}))  

class Meta:
    model = Especialidad

    fields = [

    'estadistica',

    ]

In this use the second: EstadisticaForm. What is the estimated problem? regards!

It's hard to debug this because the indentation of the code for views.py is messed up but it looks like you have an issue there. In my form handling views I usually set an if test to handle the POST case and then put the logic for the GET in the else branch. Cleaning up your view should help reveal the problem (because it looks like you have two cases in the POST case and that doesn't make sense to me). I'd also suggest you switch from render_to_response to render and get out of the habit of passing locals() , instead explicitly passing the things you need in the context. Also, it looks like you have messed up the signature of render_to_response as you are passing locals() in for your context but then passing the form explicitly. I think you've conflated two different examples of view rendering you've seen. I'm not totally clear on what you're trying to do but I think this approach is cleaner:

def ListAll(request, id_especialidad):
    template = 'index2.html'
    especialidad = Especialidad.objects.get(id=id_especialidad)
    pedido = Pedido.objects.filter(especialidad=especialidad)
    if request.method == 'POST':
        form = PedidoEditForm(request.POST, instance=especialidad)
        if form.is_valid():
            form.save()
            # return a redirect here on success
    # handles GET case and when form fails
    user = request.user
    if user.is_superuser:
        template = 'admindata.html'

    return render(request, template, {'form':form, 'pedido': pedido, 'especialidad': especialidad})

The way you've placed the if , else and endif you will never render a complete form. I'm not sure this is the cause of your problem, but certainly is a problem.

Try with this example:

<section id="contenido">
    <div class="container" style="margin:50px auto width="100%"">
        {% if especialidad.estadistica == "0" %}
        <form id="myform" method="POST">
            {% csrf_token %}
            {{form.as_p}}
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;
            <input type="submit" class= "btn btn-success" value="Guardar">
        </form>
        {% else %}
        <table id="example" class="table table-border table-striped table-hover">
            <thead>
                <tr> 
                    <td>Servicio</td>
                    <td>Cod experto</td>
                    <td>Nombre</td>
                    <td>Cantidad</td>
                    <td>Ingresar</td>
                </tr>
            </thead>
            <tfoot>
                <tr>
                    <td>Servicio</td>
                    <td>Cod experto</td>
                    <td>Nombre</td>
                    <td>Cantidad</td>
                    <td></td>
                </tr>
            </tfoot>
            <tbody>
                {% if pedido  %}
                {% for ped in pedido  %}
                <tr>
                    <td>{{ ped.especialidad.nombre }}</td>
                    <td>{{ ped.articulo.cod_experto }}</td>
                    <td>{{ ped.articulo.nombre }}</td>
                    <td>{{ ped.cantidad }}</td>
                    <td><a href="{% url "usuario:cant_ingresar" ped.id especialidad.id  %}" method='GET' type="submit" class="btn btn-primary pull-right" value="editar" onclick="document.location.reload();"/>Ingresar</a></td>

                </tr>
                {% endfor %}
                {% endif %}
            </tbody>
        </table>
        {% endif %}
    </div>
</section>

You have a broken form by the first {% if %}. If it's false, you don't have the code to open the form tag.

   {% if especialidad.estadistica == "0" %}
   <section id="contenido">
    <div class="container" style="margin:50px auto width="100%"">
     <form id="myform" method="POST"><!-- IF FALSE, NEVER RENDERS -->
    {% csrf_token %}
        ...
     {% else %}<!-- RENDER THE BEGGINING OF THE FORM AGAIN -->
     <form id="myform" method="POST"> 
    {% csrf_token %}
     </form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM