当我通过 django 模型将数据插入 postgres 数据库时发现错误,当我将csrf包放入评论中时,我的oage被成功找到,否则它显示< b>禁止错误我的代码和屏幕截图位于
之下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..")
答案 0 :(得分:0)
我不确定你为什么要手工做这么多工作。以下是您需要做的事情:
# 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字典中提取表单值而不通过表单进行验证是一个可怕的想法 - 请不要这样做。