【问题标题】:Inserting data in postgreSQL database by Django model通过 Django 模型在 postgreSQL 数据库中插入数据
【发布时间】:2015-08-16 13:54:06
【问题描述】:

当我通过 django 模型向 postgres 数据库插入数据时发现一个错误,当我将 csrf 包放在评论中时,我的 oage 被成功找到,否则它显示 禁止错误我的代码和屏幕截图如下

here is html file:

{% extends "homepage/index.html" %}
{% block title %}
Contact
{% endblock %}
{% block content %}
This is Contact us Page.
<form action="/ins/" method="POST">
{% csrf_token %}
    <table>
    <tr>
        <td>Created Date</td>
        <td><input type="text" name="cid"></td>
    </tr>
    <tr>
        <td>Updated Date</td>
        <td><input type="text" name="uid"></td>
    </tr>
    <tr>
        <td>Title</td>
        <td><input type="text" name="tid"></td>
    </tr>
    <tr>
        <td>Text</td>
        <td><input type="text" name="txid"></td>
    </tr>
    <tr>
        <td>Published Date</td>
        <td><input type="text" name="pid"></td>
    </tr>
    <tr>
        <input type="hidden" name="fdfdf" value="{{ csrf_token }}">
        <td><input type="submit" value="Insert"></td>
        <td><input type="reset" value="Reset"></td>     
    </tr>
</table>
</form>
{% endblock %}
views.py file:

def ins(request):
#c = {}
#c.update(csrf(request))
cr = request.POST.get('cid','')
up = request.POST.get('uid','')
tit = request.POST.get('tid','')
tx = request.POST.get('txid','')
pd = request.POST.get('pid','')
e = Entry(created=cr,updated=up,title=tit,text=tx,published=pd)
e.save()
    return HttpResponse("Inserted SuccessFuly..")

【问题讨论】:

  • 不用&lt;input type="hidden" name="fdfdf" value="{{ csrf_token }}"&gt;{{csrf_token}} 就可以了。
  • 重要的是,还应注意您没有对插入数据库的数据进行任何形式的验证,这是不明智的。

标签: python html django postgresql django-csrf


【解决方案1】:

我不知道你为什么要手工做这么多工作。以下是您需要做的:

# forms.py
from django import forms
from your_app.models import Entry

class EntryForm(forms.ModelForm):

    class Meta:
        model = Entry


# views.py
from django.shortcuts import render
from your_app.forms import EntryForm

def ins(request):
    form = EntryForm(request.POST or None)
    if request.method == 'POST' and form.is_valid():
        form.save()

    return render(request, 'homepage/index.html', {'form': form})


# index.html

{# code shortened for demonstration purposes #}

<form action="." method="post" enctype="application/x-www-form-urlencoded">
    {{ form.as_table }}
    {% csrf_token %}
    <button type="submit">Insert</button>
</form>

直接从 request.POST 字典中提取表单值而不通过表单验证是一个可怕的想法 - 请不要这样做。

【讨论】:

  • 同样的错误亲爱的禁止禁止 (403) CSRF 验证失败。请求中止。
  • 为什么我们把 (.) 放在这里 action="." ?
  • 抱歉,给定示例代码,csrf 验证不会失败。使用 。对于表单操作,表单将发布到加载视图的相同 url。
  • ok 版本问题,现已解决并验证成功
  • 什么样的版本问题?使用 Django 本身?
猜你喜欢
  • 1970-01-01
  • 2015-12-18
  • 1970-01-01
  • 2020-10-31
  • 2021-07-28
  • 1970-01-01
  • 2011-11-09
  • 1970-01-01
  • 2017-06-21
相关资源
最近更新 更多