带有参数的get_absolute_url [英] get_absolute_url with parameters

查看:85
本文介绍了带有参数的get_absolute_url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 urls.py

urlpatterns = [
        ...
        url(r'^profile/$', profile.profile, name='profile'),
]

我的模型

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', ???)

我的观看次数

@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查看不同的配置文件?例如,在/ admin中,当您查看个人资料 John时,单击在站点上查看,并获得包含约翰数据而不是您的个人资料的个人资料页面

Is it possible use get_absolute_url to views different profiles? For example from the /admin when you look the profile "John", you click on the "view on site" and obtain the profile page with john datas, not yours

推荐答案

您的视图必须能够接受额外的参数,最好是用户ID,因为名称通常包含空格:

Your views must be able to accept an extra argument, preferably the user id, since names usually contain spaces:

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)

这篇关于带有参数的get_absolute_url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆