Search code examples
pythonhtmldjangopostgresqldjango-csrf

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 %}
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..")

Solution

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

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

    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.