Djang中绝对路径的替代方案

2024-06-25 23:18:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个Django项目,一个商业目录。 在这里,我使用了绝对化路径进行模板渲染, 我想这可能会在将来造成问题。 请查看我的代码,并建议我如何解决这个问题,这样它就不会在将来产生任何问题。在

请帮忙

我的模型.pyis::

from django.db import models


class Directory(models.Model):

    Bussiness_name = models.CharField(max_length=300)
    Description = models.CharField(max_length=900)
    Number = models.CharField(max_length=100)
    Web_url = models.CharField(max_length=800)
    Catogory = models.CharField(max_length=200)


    def __unicode__(self):
        return self.Bussiness_name

class Adress(models.Model):
   directory =  models.ForeignKey(Directory)
   adress_name =  models.CharField(max_length=300)
   def __unicode__(self):
        return self.adress_name

class Photos(models.Model):
   directory =  models.ForeignKey(Directory)
   Photo_path =  models.CharField(max_length=100)
   Photo_name =  models.CharField(max_length=100)
   def __unicode__(self):
        return self.Photo_name

我的视图.pyis::

^{pr2}$

还有我的网址.pyis::

from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'crawler.views.home', name='home'),
    # url(r'^crawler/', include('crawler.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
    url(r'^crawlerapp/$', 'crawlerapp.views.index'),
    url(r'^crawlerapp/contactus/$', 'crawlerapp.views.contactus'),
    url(r'^crawlerapp/search/$', 'crawlerapp.views.search'),
)

我有3个html网页索引,联系我们,和搜索。 请建议一个绝对路径的替代方案,这样当我有人从GITHUB克隆它并尝试运行它时,它不会产生错误。在

请帮忙解决这个问题。在


Tags: thedjangonameselfurlincludeadminmodels
3条回答

在你的项目中设置.py文件:

在顶部加上这个

import os.path
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))

然后,要设置模板路径,请执行以下操作:

^{pr2}$

你考虑过读the Django tutorial?吗。 别忘了在设置.py文件,可以在另一个答案上找到一个好的提示;Django template Path

你应该在你的设置.py文件,位于TEMPLATE_DIRS列表中。在

不管您是否这样做,您都应该使用os.path模块的函数动态生成绝对路径。在

os.path.abspath(__file__)

将返回被调用文件的绝对路径。在

^{pr2}$

将返回'some/Path'中最后一个目录的路径

通过组合它们,你可以得到绝对路径,在不同的系统上保持精确,例如

os.path.abspath(os.path.dirname(os.path.dirname(__file__)))

将返回目录的绝对路径,该路径比包含当前文件的目录高一级。在

去阅读os.path模块的docs。您可能还需要使用os.path.join。在

相关问题 更多 >