【问题标题】:Forbidden (403) CSRF verification failed. Request aborted. Django禁止 (403) CSRF 验证失败。请求中止。姜戈
【发布时间】:2017-08-06 10:49:38
【问题描述】:

加载模板时出现这个错误表单的模型,并在文本发送我到页面帮助中输入金额 失败原因: 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。 估计问题是什么? 问候!

【问题讨论】:

标签: python django


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    您放置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>
    

    【讨论】:

      【解决方案3】:

      您的第一个 {% if %} 表单已损坏。如果为 false,则您没有打开表单标签的代码。

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

      【讨论】:

      • 还有其他的标签,你的第一个 {% if %} 没有正确处理 html 标签。
      猜你喜欢
      • 2015-03-19
      • 2018-07-16
      • 2016-08-27
      • 1970-01-01
      • 2018-11-05
      • 2018-06-06
      • 2017-06-26
      • 2019-07-22
      相关资源
      最近更新 更多