如何通过slug加载基于类的视图?

时间:2017-12-15 15:36:06

标签: python django python-3.x django-views

我创建了一个编辑用户的视图:

class UsersEditView(UpdateView):
    model = User
    fields = ['first_name', 'last_name', 'email', 'password']
    success_url = reverse('user-list')

编辑此模型:

class User(AbstractUser):
    email = EmailField(unique=True)
    slug = AutoSlugField(populate_from='email', max_length=10, unique=True)
    REQUIRED_FIELDS = []
    USERNAME_FIELD = 'email'

我用这种方式定义了网址:

urlpatterns = [
    path('', UsersListView.as_view(), name='user-list'),
    path('new/', UsersCreateView.as_view(), name='user-new'),
    path('edit/<str:slug>/', UsersEditView.as_view(), name='user-edit')
]

我测试它是这样的:

class EditUserTest(AbstractTest):

    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        user = User(email='email@provider', first_name='Test', last_name='User', slug='slug', password='qqq')
        user.save()

    def test_edit_user(self):
        response = EditUserTest.client.get(reverse('user-edit', args=('slug', )))

除了响应总是404:

ipdb> response.status_code
404

那么,我错过了什么?

这适用于Django 2.0。

1 个答案:

答案 0 :(得分:1)

你需要传递

kwargs={'slug': 'slug'}代替args=('slug', )