1
votes

This is a very old question and many similar results related to it, but I simply can not find the correct way to solve it.

I am working with Django 1.5, I have a fairly simple attempt try to use 'Post' form with Django: I created a 'note' app in Django project 'webnote', when the url is "/note/" it will simply show the form and a simple welcome information When I click the submit, I expected it will show another simple welcome1 information.

Here is the related files

note/models.py

from django.db import models
from datetime import datetime, date,time
from django.utils import timezone



class Title(models.Model):
    title =models.CharField(max_length=2000)
    def __unicode__(self):
        return self.title

note/views.py

from django.template import Context, loader
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.core.urlresolvers import reverse
from note.models import Title
from django.core.context_processors import csrf

def index(request):
    template = loader.get_template('note/index.html')
    context = Context({
                   'Name':"Guys",
                   })
    return HttpResponse(template.render(context))


def insert(request):
    #return HttpResponse("Hello World, This is the Index Page")
    return render(request, 'note/index.html', {'Name':"NewGuy"})

template/note/index.html

<html>
<body>
    Hello {{ Name }}, Welcome!  
    <form action="insert/" method="post">

        {% csrf_token %}

        <h6>Title</h6>
        <input type="text" name="title_input" value="Please Input Title">
        <input type="submit" name="SB" value="insert">
    </form>

</body>
</html>

A might not that related file is

setting.py

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (

)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'webnote',                     
        'USER': 'root',
        'PASSWORD': '',
        'HOST': '',                      
        'PORT': '3306',                     
    }
}

ALLOWED_HOSTS = []

TIME_ZONE = 'America/New_York'

LANGUAGE_CODE = 'en-us'

SITE_ID = 1

USE_I18N = True

USE_L10N = True

USE_TZ = True

MEDIA_ROOT = ''

MEDIA_URL = ''

STATIC_ROOT = ''

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

SECRET_KEY = 'gpnmov_g$zn8w@_0(s@$wlbgo2+y30*98ab*ne^)@98!zpq_w-'

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',

)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

ROOT_URLCONF = 'webnote.urls'

WSGI_APPLICATION = 'webnote.wsgi.application'

TEMPLATE_DIRS = (

    '/www/webnote/note/templates/note'
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'note'
)


LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

I tried several way mentioned in the similar(same) question in this forum. likes:

1.use render_to_response

2.Explicitly use RequestContext to replace Context

1
Could you post your urls.py aswell? - Henrik Andersson
You should try to use the reverse functionality instead of the relative insert/ path, also your view doesn't seem to provide any manner of form handling. Have you tried render_to_response('app_name/template_name.html', {}, context_instance=RequestContext(request)) - Hedde van der Heide

1 Answers

2
votes

You need to use CSRF on the view that's generating the form in the first place as well. Mostly, people use the same view for that and for processing the POST: for some reason, you've split them up into two, which is fine if you really want to but you must use the render (or RequestContext, or whatever) on the GET view too, because that's responsible for generating and outputting the token that's then checked in the POST.

So, your index view should just be:

def index(request):
    return render(request, 'note/index.html', {'Name':"Guys"})