[英]How to get user object based on username and not the (id, pk) in 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)
网址.py
urlpatterns = [
path("user/<user_id>/", views.profile_view, name = "get_profile"),
...
模型.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE, null = False, blank = True)
first_name = models.CharField(max_length = 50, null = True, blank = True)
last_name = models.CharField(max_length = 50, null = True, blank = True)
phone = models.CharField(max_length = 50, null = True, blank = True)
email = models.EmailField(max_length = 50, null = True, blank = True)
bio = models.TextField(max_length = 300, null = True, blank = True)
profile_picture = models.ImageField(default = 'default.png', upload_to = "img/%y", null = True, blank = True)
banner_picture = models.ImageField(default = 'bg_image.png', upload_to = "img/%y", null = True, blank = True)
def __str__(self):
return f'{self.user.username} 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)
网址.py
urlpatterns = [
path("user/<str:username>/", views.profile_view, name = "get_profile"),
]
确保每个user
实例都附加了profile
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.