get_absolute_url with parameters

笑着哭i 提交于 2019-12-12 20:14:27

问题


My urls.py:

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

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

My 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)

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


回答1:


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)

Then your urls.py becomes:

urlpatterns = [
        ...
        url(r'^profile/(?P<user_id>[0-9]+)/$', profile.profile, name='profile'),
]

And finally your models.py and the get_absolute_url method:

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)


来源:https://stackoverflow.com/questions/37378437/get-absolute-url-with-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!