我有一个填写在网页上的表单。表单的目标是收集一些基本信息,然后将发件人的IP也保存到数据库中。表单向我的Django视图提交POST请求,但Django给了我错误:
if request.method() == 'POST':
TypeError: 'str' object is not callable
以下是观点:
from .form import SignUpForm
from django.shortcuts import render
from django.http import HttpResponseRedirect
def index(request):
if request.method() == 'POST':
form = SignUpForm(request.POST)
if form.is.valid():
signup_item = form.save(commit=False)
signup_item.ip_address = request.META['HTTP_X_FORWARDED_FOR']
signup_item.save()
return HttpResponseRedirect(request.path)
else:
form = SignUpForm()
return render(request, 'index.html', {'form': form})
这是urls.py
from django.conf.urls.import url
from django.contrib import admin
from form import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', views.index, name='home')
]
答案 0 :(得分:2)
我认为问题在于request.method(); method是字符串数据成员,而不是成员函数。请记住 - 这是蟒蛇,其中有吸气剂'经常被拒绝直接访问班级成员。
所以,试试:
if request.method == 'POST':
form = SignUpForm(request.POST)
等
答案 1 :(得分:0)
HttpRequest.method
是表示请求中使用的HTTP方法的字符串。这保证是大写的。例如:
if request.method == 'GET':
do_something()
elif request.method == 'POST':
do_something_else()
因此,您的views.py
应该是这样的,
def index(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is.valid():
signup_item = form.save(commit=False)
signup_item.ip_address = request.META['HTTP_X_FORWARDED_FOR']
signup_item.save()
return HttpResponseRedirect(request.path)
else:
form = SignUpForm()
return render(request, 'index.html', {'form': form})