我的Django视图说它只需要一个参数而两个参数但是只有一个参数

时间:2011-08-16 16:09:59

标签: python django django-views web-frameworks

我正在研究一个django项目,当我尝试运行这个函数时,它返回只能给出一个参数,但是只给出了一个参数。

from django.http import HttpResponse, Http404
from django.template import Context
from django.template.loader import get_template
from django.contrib.auth.models import User

def main_page(request):
    template = get_template('main_page.html')
    variables = Context({
            'head_title':u'Bookmarks!',
            'page_title':u'Welcome to bookmarks!',
            'page_body': u'store and share the bookmarks',
            })
    output = template.render(variables)
    return HttpResponse(output)

网址格式

from django.conf.urls.defaults import patterns, include, url
from socialnetwork.bookmarks.views import *
urlpatterns = patterns('',
    (r'^user/(\w+)/$', main_page),

)

追溯:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/user/Colin/

Django Version: 1.3
Python Version: 2.7.1
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'socialnetwork.bookmarks']
Installed Middleware:
 ('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in   get_response
  111.                             response = callback(request, *callback_args,     **callback_kwargs)

Exception Type: TypeError at /user/Colin/
Exception Value: main_page() takes exactly 1 argument (2 given)

3 个答案:

答案 0 :(得分:10)

我怀疑您的网址格式会捕获其他一些变量。如果您将URL模式附加到视图并且该URL模式捕获任何值,则需要设置该视图以在请求参数之上为每个捕获的值获取参数,该参数始终为第一。所以,假设你有一个模式

(r'^mainpage(\d+)/$', myview)

myview()需要像这样定义:

def myview(request, digit):
    # do something

答案 1 :(得分:1)

请求始终是视图的第一个参数,除了您可能已经传递的其他参数之外。如果你调用视图传递1参数:

def main_page(request, arg1):
  code ...

答案 2 :(得分:0)

您可能通过网址传递了其他参数。