我的urls.py
:
urlpatterns = [
...
url(r'^profile/$', profile.profile, name='profile'),
]
我的model
:
class Reg(models.Model):
name = models.CharField(max_length=32, primary_key=True)
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT,
related_name='%(app_label)s_%(class)s_reg', null=True)
...
def get_absolute_url(self):
return reverse('core:profile', ???)
我的views
:
@login_required
def profile(request):
context_dict = {}
u = User.objects.get(username=request.user)
context_dict['user'] = u
r = reg.Reg.objects.get(user=u)
context_dict['reg'] = r
return render(request, 'core/reg.html', context_dict)
是否可以使用get_absolute_url查看不同的配置文件?例如,当您查看个人资料" John"时,从/ admin,您点击网站上的"视图"并获取包含john数据的个人资料页面,而不是你的
答案 0 :(得分:2)
您的视图必须能够接受额外的参数,最好是用户ID,因为名称通常包含空格:
from django.shortcuts import get_object_or_404
@login_required
def profile(request, user_id):
context_dict = {}
u = get_object_or_404(User, pk=user_id)
context_dict['user'] = u
r = reg.Reg.objects.get(user=u)
context_dict['reg'] = r
return render(request, 'core/reg.html', context_dict)
然后您的urls.py
变为:
urlpatterns = [
...
url(r'^profile/(?P<user_id>[0-9]+)/$', profile.profile, name='profile'),
]
最后是您的models.py
和get_absolute_url
方法:
class Reg(models.Model):
name = models.CharField(max_length=32, primary_key=True)
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT,
related_name='%(app_label)s_%(class)s_reg', null=True)
...
def get_absolute_url(self):
return reverse('core:profile', user_id=self.id)