TypeError:as_view()占用1个位置参数,但给出2个

时间:2016-07-01 18:56:19

标签: python django django-views

我收到了错误,我不确定它是什么意思:

TypeError at / as_view() takes 1 positional argument but 2 were given

from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin

class Employee(models.Model):
    user = models.OneToOneField(User)
    full_name = models.CharField(max_length=50)
    phone_number = models.CharField(max_length=12)
    company = models.CharField(max_length=100)
    department = models.CharField(max_length=50)
    occupation = models.CharField(max_length=50)

    class Meta:
        verbose_name_plural = 'employees'

admin.site.register(Employee)

views.py

from django.views.generic import TemplateView
from web_app.models import Employee

class EmployeeTemplateView(TemplateView):
    model = Employee.objects.all()
    template_name = 'index.html'
    context_object_name = 'employee_view'

urls.py

from django.conf.urls import url, include
from web_app import routers
from django.contrib import admin
from . import views
from web_app.views import EmployeeTemplateView
admin.autodiscover()

router = routers.DefaultRouter()
router.register(r'employee', views.EmployeeTemplateView, "Employee")

urlpatterns = ['',
               url(r'^$', EmployeeTemplateView.as_view({'emp' : 'employees'})),
               ]

我做错了什么?

提前谢谢!

3 个答案:

答案 0 :(得分:15)

确保放置" as_view()"因此。不是" as_view"。我犯了这么大的错误

答案 1 :(得分:7)

as_view不接受位置参数,它接受关键字参数。

EmployeeTemplateView.as_view(emp='employees')

答案 2 :(得分:1)

由于看起来您只是想将employees变量从视图传递到模板,您可以这样发送:

<强> views.py

from django.views.generic import ListView
from web_app.models import Employee

class EmployeeListView(ListView):
    model = Employee
    template_name = 'index.html'
    context_object_name = 'employees'

<强> urls.py

urlpatterns = [
               url(r'^$', EmployeeListView.as_view(), name="employees"),
               ]

然后您可以使用模板中的context_object_name

<强>的index.html

<div>{% for employee in employees %} {{ employee }} {% endfor %}</div>