J'ai une erreur et je ne suis pas sûr de ce que cela signifie:
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'})),
]
Qu'est-ce que je fais mal?
Merci d'avance!
as_view
ne prend pas les arguments de position, mais les mots clés.
EmployeeTemplateView.as_view(emp='employees')
Assurez-vous de mettre "as_view ()" en tant que tel. Pas "as_view". J'ai fait une si grosse erreur
Comme il semble que vous essayez simplement de transmettre la variable employees
de la vue au modèle, vous pouvez simplement l'envoyer de cette façon:
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"),
]
Ensuite, vous pouvez utiliser le context_object_name
dans le modèle de la manière suivante:
index.html
<div>{% for employee in employees %} {{ employee }} {% endfor %}</div>