在Django

时间:2017-10-16 15:06:05

标签: python django

我的问题类似于 Same URL in multiple views in Django ,但我不是基于user_authentication渲染模板,而是基于在浏览器中启用或禁用的JavaScript。

我想做什么?

如果在浏览器中启用了JavaScript,我正在尝试呈现index.html页面,否则我想在jsDisabled.html页面呈现,如果它被禁用,并且两个页面都应该呈现在相同的URL模式上,例如:

如果在浏览器中启用了JavaScript,那么

localhost:8000应该呈现index.html,如果禁用JavaScript,它应该呈现jsDisabled.html页面。

注意:我正在检查浏览器中是否使用<noscript>标记禁用了JavaScript,该标记将在禁用JavaScript时运行。

到目前为止,这是我的代码:

base.html文件:

{% load staticfiles %}

<!DOCTYPE html>
<html>
    <head>
    </head>

    <body class="noJs">
        ...
        <a href="{% url 'index' 0 %}"> abc </a>
        ...
        <noscript>
            <style type="text/css">
                .noJs {
                    display: none;
                }
            </style>
            <meta http-equiv="refresh" content="{% ulr 'index' 1 %}"> /* This should render jsDisabled.html page on the same URL which is 'localhost:8000' */

        </noscript>
    </body>
</html>

urls.py:

from django.conf.urls import include, url
from django.contrib import admin
from . import views

urlpatterns = [
  ...
  url(r'^(?P<flag>[0-1])$', views.index, name='index'),
]

views.py:

from django.shortcuts import render

def index(request, flag):
    if (flag):
       return render(request, 'jsDisabled.html')
    else:
       return render(request, 'index.html')

2 个答案:

答案 0 :(得分:1)

根据您的Django版本,您可能需要在settings.py中指定TEMPLATE_DIR =(在较新版本中,这不是必需的)。

以下是模板和代码逻辑上的一些有用的information

Main/templates/myapp/base.html
Main/templates/myapp/index.html
Main/templates/myapp/includes/yes_js.html
Main/templates/myapp/includes/no_js.html

base.html文件:

{% load staticfiles %}

<!DOCTYPE html>
<html>
<head>
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>

的index.html:

{% extends 'myapp/base.html' %}
{% load staticfiles %}

{% block content %}
<noscript>
{% include 'no_js.html' %}
</noscript>

{% include 'yes_js.html' %}

{% endblock %}

答案 1 :(得分:0)

经过大量的调试后我终于找到了解决办法:)这就是:

base.html文件:

{% load staticfiles %}

<!DOCTYPE html>
<html>
<head>
</head>
<body>
 <div class="noJs">
    ...
    <a href="{% url 'index' 0 %}"> abc </a>
    ...
 </div>
 <noscript>
    <style type="text/css">
        .noJs {

            display: none;
       }
    </style>
    {% include 'includes/jsDisabled.html' %}
</noscript>
</body>
</html>

urls.py

from django.conf.urls import include, url
from django.contrib import admin
from . import views

urlpatterns = [

   url(r'^admin/', admin.site.urls),
   url(r'^articles/', include('articles.urls')),
   url(r'^contact/', include('contact.urls')),
   url(r'^temp/',views.temp, name="temp"),
   url(r'^$', views.index, name='index'),
]

views.py:

from django.shortcuts import render

def index(request):
    return render(request,'index.html')

def temp(request):
     return render(request,'temp.html')

我将include内置模板标记包含为@noes1s建议的{% include 'includes/jsDisabled.html' %},方法是在模板文件夹中创建一个名为includes的文件夹并放置jsDisabled.html在里面。