有这个代码:
#urls.py
path('', MainFormView.as_view(), name='home'),
path('index', MainFormView.as_view(), name='home'),
path('home', MainFormView.as_view(), name='home'),
...
#base.html
{% if request.path == '/home' %}
{{ блок }}
{% endif %}
一页有多个地址。此页面应显示一个块,但条件是一种方式。如何在条件中不枚举的情况下简洁地做到这一点?或者如何从第一条和第二条路径重定向到第三条?
UDP代码view
:
@method_decorator(login_required, name='dispatch')
class MainFormView(DataMixin, FormView):
form_class = MainForm
template_name = 'sitee/index.html'
success_url = reverse_lazy('home')
def get_context_data(self, *, object_list=None, **kwargs):
context = super().get_context_data(**kwargs)
context['menu_selected'] = 'home'
c_def = self.get_user_context(title="Главная")
return dict(list(context.items()) + list(c_def.items()))
def form_valid(self, form):
print(form.cleaned_data)
return redirect('home')
可以通过三种方式访问该页面:
127.0.0.1
127.0.0.1/index
127.0.0.1/home
如何使当你尝试去127.0.0.1
而127.0.0.1/index
我们被转移到127.0.0.1/home
?这是必要的,这样模板才会有这样的条件if request.path == '/home'
,而不是这样。if request.path == '/home' or request.path == '/index' or request.path == '/'
或者你可以不做重定向就离开它,并在条件中使用类似这样的东西:if request.name == 'home'
,即 如果指定了页面名,不管它的路径是什么,都满足条件
#urls.py
#base.html
要在 urls.py 中获取“名称”,您可以使用 {{ request.resolver_match.view_name }}。所以您可以这样做。