【问题标题】:Django "if request.method == 'POST':" failsDjango“如果request.method =='POST':”失败
【发布时间】:2014-12-07 11:06:47
【问题描述】:

您好,在我的新 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/')

就在“else”之后

if request.method == 'POST':

声明,当我尝试访问表单 URL 时,我什至无法填写表单。它把我直接带到/thanks/。所以 request.method 检查总是失败。

我错过了什么??

【问题讨论】:

  • 控制台有错误吗?如果您的请求是 POST 请求,但表单无效,会发生什么情况?您确定将有效数据传递给您的表单吗?尝试调试代码:在if 语句之前粘贴import pdb; pdb.set_trace()。当解释器“命中”这一行时,您将在控制台中得到一个“愚蠢的”Python shell。在这种情况下 request.method 说明了什么?
  • 如果将重定向放在 else 之后,您所描述的行为正是您所期望的:当您最初加载页面时,方法是 GET。
  • pdb.set_trace()fails with No exception message supplied

标签: html django post


【解决方案1】:

问题解决了:

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

来自jqBootstrapValidation 导致了这个问题。我不太清楚为什么,但一定是某些表单功能受到了干扰。

谢谢你的帮助

【讨论】:

    【解决方案2】:

    您的模板代码中有错误:{ form.as_p }} add '{'

    【讨论】:

      【解决方案3】:

      我尝试了以下方法:

      如果表单域是

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

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

      如果我将字段定义为

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

      我点击了无名提交,但确实收到 Django 表单字段错误

      【讨论】:

      • 请使用您问题上的编辑链接添加更多信息。 Post Answer 按钮应仅用于问题的完整答案。
      • 这没有提供问题的答案。要批评或要求作者澄清,请在他们的帖子下方发表评论 - 您可以随时评论自己的帖子,一旦您有足够的reputation,您就可以comment on any post
      猜你喜欢
      • 1970-01-01
      • 2021-09-30
      • 2018-01-30
      • 1970-01-01
      • 2014-05-04
      • 2021-05-20
      • 2013-02-08
      • 2014-07-04
      • 2021-08-15
      相关资源
      最近更新 更多