Using Form in Django - get() missing 1 required po

2019-08-03 03:45发布

问题:

currently working in Django and trying to do a simple tutorial on forms, but I am receiving an error when the form is submitted.

Here is my urls.py:

from .views import*
urlpatterns = [
url(r'^name/', get_name, name='TheName'),
url(r'^name/present/', present, name='Present'),
]

Here are the views:

def get_name(request):
   if request.method == 'POST':
    form = NameForm(request.POST)
    if form.is_valid():
        return HttpResponseRedirect
   else:
    form = NameForm()

   return render(request, 'home/name.html', {'form': form})


def present(request):
   return render(request, 'home/present.html')

Here is the form:

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

Here is name.html:

<form action="present/" method="post">
   {% csrf_token %}
   {{ form }}
   <input type="submit" value="Submit" />
</form>

Here is my present.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>{{ your_name }}</title>
</head>
<body>

</body>
</html>

After submit is clicked, and error message with the traceback:

Environment:

Request Method: POST
Request URL: http://localhost:8000/name/present/

Django Version: 1.11.4
Python Version: 3.6.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File   "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
41.             response = get_response(request)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/deprecation.py" in __call__
142.             response = self.process_response(request, response)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/middleware/clickjacking.py" in process_response
32.         if response.get('X-Frame-Options') is not None:

Exception Type: TypeError at /name/present/
Exception Value: get() missing 1 required positional argument: 'header'

Any help would be appreciated!

回答1:

You need to tell where to redirect after successful form submission. You are only doing return HttpResponseRedirect which is not valid, instead it should be:

return HttpResponseRedirect(the_path_to_redirect_to)

Please read documentation about HttpResponseRedirect.