Возврат конкретного пользователя в Django

Я все еще довольно новичок в Django и пытаюсь разобраться, как отобразить профиль текущего пользователя при нажатии на кнопку 'view profile' в навигационной панели и конкретного пользователя при нажатии на кнопку 'view profile' на странице чужого проекта. В настоящее время при нажатии на навигационную панель корректно отображается профиль текущего пользователя, однако при нажатии для просмотра чужой страницы на странице детализации проекта все равно отображается текущий пользователь, а не страница профиля нужного пользователя.

I still want the url to show up like so: 'accounts/username/view_profile' and not 'accounts/pk/view_profile'

Я пытался использовать метод 'get_context_data' в моем ViewProfileView, но он возвращает ошибку о вызове url со slugs или object pk.

models.py I think I have the slug properly set up but I'm not sure how to implement it or if that will even solve my problem here - I've tried adding the slug to the url-conf and passing it through the get_context_data in views.py but I could never get it to work properly, just error after error.

...
class Profile(models.Model):
    user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    slug = models.SlugField(blank=True, db_index=True, unique=True)
    about = models.TextField(max_length=500, null=True, blank=True) 
    profile_pic = models.ImageField(null=True, blank=True, upload_to="images/profile")
    facebook_url = models.CharField(max_length=255, null=True, blank=True)
    twitter_url = models.CharField(max_length=255, null=True, blank=True)
    instagram_url = models.CharField(max_length=255, null=True, blank=True)
    linkedin_url = models.CharField(max_length=255, null=True, blank=True)
    github_url = models.CharField(max_length=255, null=True, blank=True)

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = self.user.username
        super(Profile, self).save(*args, **kwargs)
...

views.py Здесь вы можете увидеть мою попытку get_context_data. get_object возвращает текущего пользователя, что работает при навигации через панель навигации, но не при навигации через пост проекта другого человека. Есть ли способ сделать его динамическим, чтобы я мог возвращать get_object, если запрос выполняется через панель навигации, и что-то другое, если запрос выполняется через страницу профиля?

...
class ViewProfileView(generic.DetailView):
    model = Profile
    template_name = 'registration/view_profile.html'

    def get_object(self):
        return self.request.user.profile

    # def get_context_data(self, *args, **kwargs):
    #     users = Profile.objects.all()
    #     ctx = super(ViewProfileView, self).get_context_data(*args, **kwargs)

    #     page_user = get_object_or_404(Profile, id=self.kwargs['username'])

    #     ctx['page_user'] = page_user
    #     return ctx
...

urls.py

...
app_name = 'accounts'

urlpatterns = [
    path('signup/', SignUpView.as_view(), name='signup'),
    path('<str:username>/edit_user/', EditUserView.as_view(), name='edit_user'),
    path('password/', ChangePasswordView.as_view(), name='change-password'),
    path('password_success/', password_success, name='password_success'),
    path('<str:username>/view_profile/', ViewProfileView.as_view(), name='view_profile'),
    path('<str:username>/edit_profile/', EditProfileView.as_view(), name='edit_profile')
]

base.html (nav-bar, going to self - works)

...
<a class="dropdown-item" href="{% url 'accounts:view_profile' user.username %}">View Profile</a>
...

project_detail.html (going to another user's profile but returns self, does not work)

...
<a href="{% url 'accounts:view_profile' project.owner.username %}">View Profile</a><br></small></i>
...

Благодарим вас за уделенное время! Любая помощь очень, очень ценится! Будьте здоровы

Вам нужно вернуть объект Profile, который связан с пользователем с заданным именем пользователя, так:

from django.shortcuts import get_object_or_404

class ViewProfileView(generic.DetailView):
    model = Profile
    template_name = 'registration/view_profile.html'

    def get_object(self):
        return get_object_or_404(Profile, user__username=self.kwargs['username'])

В шаблоне вы работаете с object, например, вы можете визуализировать:

{{ object.user.username }}: {{ object.about }}
Вернуться на верх