禁止(403)CSRF验证失败。请求中止。 Django的

时间:2017-03-15 15:30:05

标签: python django

我在将模板加载到表单模型时遇到此错误,并在文本中输入数量将我发送到页面帮助 失败的原因: CSRF符号缺失或不正确。来自Django,请帮忙!

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})

模板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%}

模型形式:

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',

    ]

在此使用第二个:EstadisticaForm。 估计的问题是什么? 问候!

3 个答案:

答案 0 :(得分:1)

很难对此进行调试,因为views.py代码的缩进是混乱的,但看起来你有问题。在我的表单处理视图中,我通常设置一个if测试来处理POST情况,然后将GET的逻辑放在else分支中。清理视图应该有助于揭示问题(因为看起来你在POST案例中有两个案例,这对我来说没有意义)。我还建议您从render_to_response切换到render,并且不再需要传递locals(),而是在上下文中明确传递您需要的内容。此外,当您为您的上下文传递locals()但后来明确传递表单时,您似乎搞砸了render_to_response的签名。我想你已经把两个不同的视图渲染示例混为一谈了。我不清楚你要做什么,但我认为这种方法更清洁:

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})

答案 1 :(得分:0)

您放置ifelseendif的方式永远不会呈现完整的表单。我不确定这是你问题的原因,但肯定是个问题。

试试这个例子:

<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>

答案 2 :(得分:0)

第一个{%if%}的表单已损坏。如果它是错误的,您就没有代码来打开表单标记。

   {% 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>