Django"如果request.method ==' POST':"失败

时间:2014-10-12 22:18:32

标签: html django post

你的新Django项目有一个奇怪的问题。

我基本上测试了Django Documentation Working with Froms中的 NameForm 示例。这似乎是一个简单的,但不知何故,当我尝试提交一些名称时,即使没有页面重新加载也没有任何反应。

form.py

from django import forms

class NameForm(forms.Form):
     your_name = forms.CharField(label='Your name', max_length=100)

views.py

from django.shortcuts import render
from django.http import HttpResponseRedirect
from groupbuilder import forms

def GroupBuilder(request):
    if request.method == 'POST':
        form = forms.NameForm(request.POST)
        if form.is_valid():
            return HttpResponseRedirect('/thanks/')

    else:
        form = forms.NameForm()


    return render(request, 'groupbuilder.html', {'form': form})

模板:

    <form action="/your-name/" method="post">
          {% csrf_token %}
          { form.as_p }}
          <input type="submit" value="Submit" />
    </form>

setting.py

"""
Django settings for crossLFG project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
from django.utils.translation import ugettext_lazy as _

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.core.context_processors.tz",
    "django.contrib.messages.context_processors.messages",
    #"frontpage.context_processors.contactform",
)


DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)

MANAGERS = ADMINS

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
PROJECT_PATH = '/home/KBrothers/crossLFG/'
TEMPLATE_PATH = os.path.join(PROJECT_PATH, 'templates')
STATIC_PATH = os.path.join(PROJECT_PATH,'static')
STATIC_URL = '/static/'
DATABASE_PATH = os.path.join(PROJECT_PATH,'users.db')
#LOCALE_PATHS = os.path.join(PROJECT_PATH, 'locale',)
LOCALE_PATHS = ('/home/KBrothers/crossLFG/locale',)



# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ****

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

CRISPY_TEMPLATE_PACK = 'bootstrap3'

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'accounts',
    'main_app',
    'groupbuilder',

    'crispy_forms',

)



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

TEMPLATE_DIRS = (
    os.path.join(PROJECT_PATH, 'templates'),
    os.path.join(PROJECT_PATH, 'main_app/templates'),
    os.path.join(PROJECT_PATH, 'accounts/templates'),
    os.path.join(PROJECT_PATH, 'groupbuilder/templates'),

)

MIDDLEWARE_CLASSES = (
     'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    'django.middleware.clickjacking.XFrameOptionsMiddleware',

)

ROOT_URLCONF = 'crossLFG.urls'

WSGI_APPLICATION = 'crossLFG.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

MAIL_USE_TLS = True
EMAIL_HOST = '****'
EMAIL_PORT = ****
EMAIL_HOST_USER = '********'
EMAIL_HOST_PASSWORD = '********'

#CRISPY_TEMPLATE_PACK = 'bootstrap3'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': DATABASE_PATH,                      # Or path to database file if using sqlite3.
        # The following settings are not used with sqlite3:
        'USER': '',
        'PASSWORD': '',
        'HOST': '',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
        'PORT': '',                      # Set to empty string for default.
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en'
#LANGUAGE_CODE = 'de'
#LANGUAGE_CODE = 'fr'
LANGUAGE_COOKIE_NAME = 'wm_lang'
TIME_ZONE = 'UTC'

LANGUAGES = (

    ('en', _('English')),
    #('de', _('German')),
    #('fr', _('French')),
)







USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

奇怪的是,如果我把

return HttpResponseRedirect('/thanks/')

&#34; else&#34;在

if request.method == 'POST':

声明,当我尝试访问表单URL时,我甚至无法填写表单。它需要我直接/感谢/。所以request.method检查总是失败。

我想念什么?

3 个答案:

答案 0 :(得分:1)

问题解决了:

<script src="{{STATIC_URL}}js/plugins/jqBootstrapValidation.js"></script>
来自jqBootstrapValidation

导致了这个问题。我不太清楚为什么,但必须对某些形式的功能有所干扰。

无论如何,谢谢你的帮助

答案 1 :(得分:0)

您的模板代码出错:{ form.as_p }}添加&#39; {&#39;

答案 2 :(得分:0)

我尝试了以下内容:

如果表单字段是

your_name = forms.CharField(label='Your name', max_length=5, required = True)

我只是点击提交按钮而没有填写名称,没有任何反应。没有重新加载页面,没有错误消息(因为字段设置为“required”)。

如果我将字段定义为

your_name = forms.CharField(widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=("our name"))

我点击提交没有名字我得到一个Django表单字段错误