Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Django Forms to Add to Database

I am trying to use this form to add to a table in the database. I am currently getting the error "CSRF verification failed. Request aborted.," but I was getting others errors with different tweaks to this code. How do I get this code to work and what is the best practice for writing a form like this?

models.py

from django.db import models
from django.contrib.auth.models import User

class Portfolio(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=30)
    description = models.CharField(max_length=100)

    def __unicode__(self):
        return self.name

forms.py

from django import forms

class CreatePortfolio(forms.Form):
    name = forms.CharField(max_length=30)
    description = forms.CharField(max_length=100)

views.py

from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.core.context_processors import csrf
from portfolio.models import Portfolio
from portfolio.forms import CreatePortfolio

def portfolio(request):
    if request.method == 'POST':
        portfolio_form = CreatePortfolio(request.POST)
        if form.is_valid():
            csrf_token = django.middleware.csrf.get_token(request)
            port_name = form.cleaned_data['name']
            port_description = form.cleaned_data['description']
            port_user = request.user
            new_portfolio = Portfolio(name=port_name, description=port_description, user=port_user)
            new_portfolio.save()
            return render_to_response('portfolio.html', {'csrf_token': csrf_token})
    else:
        portfolio_form = CreatePortfolio()
    return render_to_response('portfolio.html', {'portfolio_form': portfolio_form})

portfolio.html

<form method="post" action="">
    {% csrf_token %}
    <div class="field">
        <label for="id_name">Name:</label>
            {{ portfolio_form.name}}
    </div>
    <div class="field">
        <label for="id_description">Description:</label>
        {{ portfolio_form.description }}
    </div>
    <input type="submit" value="Create">
</form>
like image 619
user1330225 Avatar asked Feb 17 '26 00:02

user1330225


1 Answers

You do not have to explicitly send the csrf_token. Django takes care of it for you.

Every time a form is submitted, it verifies the token, and generates a new token for subsequent requests. Here, you are forcing it to use the same token, hence the error.

Your view should look something like this:

def portfolio(request):
    if request.method == 'POST':
        portfolio_form = CreatePortfolio(request.POST)
        if form.is_valid():
            port_name = form.cleaned_data['name']
            port_description = form.cleaned_data['description']
            port_user = request.user
            new_portfolio = Portfolio(name=port_name, description=port_description, user=port_user)
            new_portfolio.save()
            return render_to_response('portfolio.html', {}, context_instance=RequestContext(request))
    else:
        portfolio_form = CreatePortfolio()
    return render_to_response('portfolio.html', {'portfolio_form': portfolio_form}, context_instance=RequestContext(request))
like image 171
karthikr Avatar answered Feb 18 '26 13:02

karthikr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!