使用 user_username 而不是 user_id 访问用户配置文件

Using the user_username instead of user_id to access a user profile

如何通过用户名而不是 ID 访问模型对象,或者如何将用户名转换为可用于访问模型对象的 ID?

我有如下视图,其中传入的参数是 user_username:

views.py

def profile_page(request, user_username):
    form = FollowUserForm(request)
    profile = Profile.objects.get(user=user_username)
    return render(request, "network/profilePage.html", {
        "form": form,
        "profile": profile
    })

我知道我们不能让用户等于 user_username 那么有没有一种方法可以将用户名以某种方式转换成一个 id,然后我可以用它来访问相关的 Profile 对象?我这样做是因为在我的 urls.py 中,我希望 url 显示用户的用户名而不仅仅是数字 ID。

urls.py

path("profile/<str:user_username>", views.profile_page, name="profile"),

编辑添加:

models.py

class User(AbstractUser):
    pass


class Profile(models.Model):
    user = models.OneToOneField("User", on_delete=models.CASCADE, primary_key=True)
    friends = models.ManyToManyField("User", related_name='following', blank=True, symmetrical=False)

您可以过滤 username 用户:

from django.shortcuts import get_object_or_404

def profile_page(request, user_username):
    profile = get_object_or_404(Profile<b>, user__username=user_username</b>)
    form = FollowUserForm(request)
    return render(request, 'network/profilePage.html', {
        'form': form,
        'profile': profile
    })

Note: It is often better to use get_object_or_404(…) [Django-doc], then to use .get(…) [Django-doc] directly. In case the object does not exists, for example because the user altered the URL themselves, the get_object_or_404(…) will result in returning a HTTP 404 Not Found response, whereas using .get(…) will result in a HTTP 500 Server Error.