【问题标题】:Django url template tag: 'module' object has no attribute 'views'Django url模板标签:'module'对象没有属性'views'
【发布时间】:2009-11-14 06:02:33
【问题描述】:

有问题的标签:

< a href="{% url django.contrib.auth.views.login %}">Login< /a>

URLConf:

from django.contrib.auth import views <br />
...<br />
(r'^login/$',views.login, {'redirect_field_name' : '/' })
<br />...

【问题讨论】:

    标签: django templates


    【解决方案1】:

    最好使用命名的 url,它们可以节省大量的维护工作,并在第一时间输入。

    如果您保持 url 的名称相同,您可以重命名视图函数,将其移动到不同的应用程序等。您根本不需要使用此 url 更改模板或其他地方。

    在 urls.py 中:

    url(r'^login/',path.to.view,name='login',...)
    

    在模板中:

    <a href="{%url login%}">login here</a>
    

    在视图中:

    login_url = reverse('login')
    

    【讨论】:

      【解决方案2】:

      由于某种原因,它不喜欢我导入它的方式。

      解决方案:

      from django.contrib.auth.views import login
      
      (r'^login', login, etc.)
      

      【讨论】:

        【解决方案3】:

        我相信我对这个问题有一些贡献。

        对我来说奇怪的是,我的代码在我使用它的方式上是有意义的,但它不起作用。

        如果在我的网址中,我尝试了以下操作。 helloworld 是我的 django 应用程序名称。

        import helloworld
        ...
        url(r'^test', helloworld.views.home1() , name='home'),
        

        它会产生错误。即使从技术上讲,每件事都是正确的。我已经导入了我的应用程序,这是一个由 django manage startapp 自动创建的 python 模块

        module' object has no attribute 'views'
        

        我在 github 上找到了 django project site 的源代码,并查看了他们如何在应用程序的 urls 部分进行导入。去看看这个项目在 github 上。是大型项目实施的绝佳参考。那里有很多东西要学。 https://github.com/django/djangoproject.com.

        这就是他们进行导入和 url 配置的方式。

        from accounts import views as account_views
        ...
        url(r'^~(?P<username>[\w-]+)/$', account_views.user_profile, name='user_profile'),
        

        所以我将我的代码修改为类似的东西

        import helloworld.views as helloView
        ...
        url(r'^test', helloView.home1 , name='home'),
        

        这很可能与 app/project/python 命名空间有关。我不完全确定。但是我的代码按预期工作,我仍然可以在各自的命名空间中拥有不同的应用程序。我只需要确保 import app.view as somename 在 app / project / python 命名空间方案中是唯一的。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-01-14
          • 2014-08-15
          • 1970-01-01
          • 1970-01-01
          • 2019-08-13
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多