Sidy Funda Sidy Funda - 1 year ago 90
Python Question

Inserting data in postgreSQL database by Django model

i found an error when i insert data to postgres database by django model,when i put csrf package in comment then my oage was found successfully else its shows an forbidden error my code and screen shot is below

here is html file:

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

def ins(request):
#c = {}
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)
return HttpResponse("Inserted SuccessFuly..")

Answer Source

I'm not sure why you're doing so much work by hand. Here's what you need to do:

from django import forms
from your_app.models import Entry

class EntryForm(forms.ModelForm):

    class Meta:
        model = Entry

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():

    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>

Pulling form values directly out of the request.POST dictionary without passing them through your form's validation is a horrible idea - please don't do that.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download