Generic detail view UserProfileDetailView must be called with either an object pk or a slug in the URLconf

前端 未结 3 1450
长发绾君心
长发绾君心 2021-01-22 16:37

Well I am facing error and it\'s now its been two days to this question and still stuck on this mistake, anybody can help and able to fix this. I am new in Django and need help.

3条回答
  •  臣服心动
    2021-01-22 17:16

    Problem

    1. str type used instead of slug type in urls.py
    2. UserProfileDetailView doesn't specify your custom slug_url_kwarg and slug_field
    3. UserProfileDetailView specifies UserProfile model but UserProfile model doesn't have attribute or method username, which is on `User table.

    Solution

    Reading Django's DetailView code, you'll find that the following is necessary to get your code working properly.

    Update class attributes

    views.py

    class UserProfileDetailView(DetailView):
        slug_url_kwarg = "username"
        slug_field = "username"
    

    Update UserProfile model OR Update UserProfileDetailView.get_slug_field

    UserProfile is the lookup table defined for UserProfileDetailView and get_slug_fieldmethod, which readsslug_fieldproperty on the UserProfileDetailView doesn't support dot syntax method traversal (ie:user.username`). Thus either:

    1. UserProfile model must have reference to username or;
    2. get_slug_field must explicitly define slug field or;
    3. get_slug_field must add functionality for dot syntax method traversal

    models.py

    class UserProfile(models.model):
        ...
        
        @property
        def username(self):
            self.user.username 
    

    OR

    class UserProfileDetailView(DetailView):
        ...
    
        def get_slug_field(self):
            self.user.username
    

    Update username type in urls.py

    Helpful, but not necessary.

    urls.py

    path('/', UserProfileDetailView.as_view(), name = 'detail'),
    

    References

    Django Detail View get_slug_field (Github): https://github.com/django/django/blob/master/django/views/generic/detail.py#L78-L80

提交回复
热议问题