Как получить объект пользователя на основе имени пользователя, а не (id, pk) в Django
У меня проблемы с просмотром других профилей с именем пользователя в URL, я могу видеть их страницы с ID пользователей, но не с их именами, вот такой url сейчас http://127.0.0.1:8000/user/30/, но я хочу иметь такой http://127.0.0.1:8000/user/reedlyons/. Я знаю, что могу сделать это с помощью get_object_or_404, но мне интересно, есть ли другой способ обойти это.
Вот мой views.py
def profile_view(request, *args, **kwargs):
context = {}
user_id = kwargs.get("user_id")
try:
profile = Profile.objects.get(user=user_id)
except:
return HttpResponse("Something went wrong.")
if profile:
context['id'] = profile.id
context['user'] = profile.user
context['email'] = profile.email
context['profile_picture'] = profile.profile_picture.url
return render(request, "main/profile_visit.html", context)
urls.py
urlpatterns = [
path("user/<user_id>/", views.profile_view, name = "get_profile"),
...
def profile_view(request, username):
context = {}
try:
user = User.objects.get(username=username)
profile = user.profile
context['username'] = user.username
context['email'] = profile.email
context['bio'] = profile.bio
context['profile_picture'] = profile.profile_picture.url
except User.DoesNotExist:
return HttpResponse("Something went wrong.")
return render(request, "main/profile_visit.html", context)
urls.py
urlpatterns = [
path("user/<str:username>/", views.profile_view, name = "get_profile"),
]
убедитесь, что каждый экземпляр user
, присоединенный с помощью profile