1
votes

I am very new to Django forms. I am trying to simply get a value from a text field and store it in a database. I am getting an error report saying:

*Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: CSRF token missing or incorrect.

For POST forms, you need to ensure:

Your browser is accepting cookies.

The view function uses RequestContext for the template, instead of Context.

In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.

If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.*

Where am I going wrong?

My views.py code is:

from django.shortcuts import render
from feedback.models import Test
from mysite.forms import TestForm
from django.http import HttpResponse
from django.template import Context, loader

def test_view(request):
    form = TestForm
    t = loader.get_template('form.html')
    c = RequestContext(request,{'n':''})
    if request.method=='POST':
        form = TestForm(request.POST)
        if form.is_valid():
            in_name = request.POST.get("firstname")
            fd = Test(name = in_name)
            fd.save()
    return HttpResponse(t.render(c))

My models.py code is:

from django.db import models
from django.forms import ModelForm

class Test(models.Model):
      name = models.CharField(max_length=255)

class TestForm(ModelForm):
      class Meta:
           model = Test
           fields = ['name']

My forms.py code is:

from django import forms

class TestForm(forms.Form):
      name = forms.CharField()

My HTML template is:

<!DOCTYPE html>
<html>
<head>
     <title>test form</title>
</head>

<body>

<form method = "POST">
{% csrf_token %}
First name:<br>
<input type="text" name="firstname" value = {{ n }}>
<br><br><br>
<input type="submit" value="Submit">
</form>
</body>

</html>
1

1 Answers

0
votes

You do it in a wrong, very PHPish, way.

Move the form definition from models.py to the forms.py, so your feedback/forms.py should be:

from django.forms import ModelForm

class TestForm(forms.ModelForm):
      class Meta:
           model = Test
           fields = ['name']

The feedback/views.py should be simplified to:

from django.shortcuts import render, redirect

from feedback.forms import TestForm

def test_view(request):
    if request.method == 'POST':
        form = TestForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('.')
    else:
        form = TestForm()
    return render(request, 'form.html', {'form': form})

And the template:

<!DOCTYPE html>
<html>
<head>
     <title>test form</title>
</head>

<body>

    <form method="POST">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="Submit">
    </form>

</body>

</html>