如何在Django中使用DetailView类重定向URL?

时间:2012-03-25 20:26:24

标签: django django-urls

在我决定使用DetailView之前,我使用this solution进行了网址重定向。

现在我正在使用DetailView如何实现相同的重定向?由于我在name LOGIN_REDIRECT_URL中使用settings.py,因此urls.py必须相同。

以下是urlpatterns = patterns( 'doors.views', url( r'^users/$', ListView.as_view( model = User, template_name = 'doors/users/list.html' ), ), url( r'^users/(?P<pk>\d+)/$', DetailView.as_view( model = User, template_name = 'doors/users/detail.html' ), name = 'users_detail' ), url( r'^users/self/$', # do some kind of redirect 'users_self_detail', name = 'users_self_detail' ), ) 的部分内容

{{1}}

3 个答案:

答案 0 :(得分:3)

Check the docs out for decorating urls when using class based views

from django.contrib.auth.decorators import login_required
urlpatterns = patterns( 'doors.views',
    url(r'^users/$',login_required(ListView.as_view(model = User,template_name = 'doors/users/list.html')),
    ...
),

答案 1 :(得分:1)

我们不要调用此重定向,因为这会与HTTP重定向混淆。我们只是说我们希望视图的行为相同,即它们应该以相同的代码和方式结束。模板。这是我自己子类DetailView的地方。类似的东西:

class UserDetailView(DetailView):
    model = User
    template_name = 'doors/users/detail.html'

class SelfUserDetailView(UserDetailView):
    def get_object(self):
       return self.request.user

然后在urls.py

from django.contrib.auth.decorators import login_required
from myapp.views import UserDetailView, SelfUserDetailView
url(r'^users/(?P<pk>\d+)/$', UserDetailView.as_view(), name='users_detail'),
url(r'^users/self/$', login_required(SelfUserDetailView.as_view()), name='users_self_detail'),

答案 2 :(得分:0)

这是在Django 2中执行此操作的2种方法。 您可以在

中创建视图并定义模板路径

1)在URL文件中创建视图并在那里定义路径

from django.urls import  path
from django.views.generic import ListView, DetailView
from crm.models import Organisation

urlpatterns = [
    path('org/<int:pk>', DetailView.as_view(model=Organisation, 
template_name = 'crm/org/org_detail_main.html'))

2)在视图中创建单独的视图并在其中定义显式模板

所以这里是 urls

from django.urls import include, path
from crm.views import OrganisationDetailView

urlpatterns = [
    path('org/<int:pk>',OrganisationDetailView.as_view(), 
    name='organisation_detail')

视图

from .models import Activity, Organisation
from django.views.generic.detail import DetailView


class OrganisationDetailView(DetailView):

    model = Organisation
    template_name = 'crm/org/org_detail_main.html'