【问题标题】:Alternative for Absolute Path in DjangoDjango中绝对路径的替代方案
【发布时间】:2013-07-13 16:28:01
【问题描述】:

我正在制作一个 Django 项目,一个企业目录。 这里我使用 ABSOULATE PATHS 进行模板渲染, 我认为这可能会在将来产生问题。 请查看我的代码并建议我如何解决此问题,以免将来产生任何问题。

请帮忙

我的models.py是::

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

我的 view.py 是 ::

# Create your views here.
from django.http import HttpResponse
from crawlerapp.models import Directory
from crawlerapp.models import Adress
from crawlerapp.models import Photos
from django.template import Context, loader
from django.shortcuts import render

def index(request):
    Directory_list = Directory.objects.all()
    t=loader.get_template('C:/Python27/django/crawler/templates/crawlertemplates/index.html')
    c = Context({'Directory_list': Directory_list,})
    return HttpResponse(t.render(c))

def contactus(request):
    Directory_list = Directory.objects.all()
    t=loader.get_template('C:/Python27/django/crawler/templates/crawlertemplates/contactus.html')
    c = Context({'Directory_list': Directory_list,})
    return HttpResponse(t.render(c))

def search(request):
    if 'what' in request.GET and request.GET['what']:
        what = request.GET['what']
        crawlerapp = Directory.objects.filter(Catogory__icontains=what)
        return render(request, 'C:/Python27/django/crawler/templates/crawlertemplates/search.html',
                  {'crawlerapp': crawlerapp, 'query': what})

    elif 'who' in request.GET and request.GET['who']:
        who = request.GET['who']
        crawlerapp = Directory.objects.filter(Bussiness_name__icontains=who)
        return render(request, 'C:/Python27/django/crawler/templates/crawlertemplates/search.html',
                  {'crawlerapp': crawlerapp, 'query': who})

    else:
        message = 'You submitted an empty form.'
    return HttpResponse(message)

而我的 urls.py 是::

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 克隆它并尝试运行它,它就不会产生错误。

请帮忙解决这个问题。

【问题讨论】:

    标签: python django django-models django-templates django-views


    【解决方案1】:

    您应该在 TEMPLATE_DIRS 列表中的 setting.py 文件中列出您是模板目录。

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

    os.path.abspath(__file__)
    

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

    os.path.dirname('some/path')
    

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

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

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

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

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

    【讨论】:

      【解决方案2】:

      您是否考虑阅读the Django tutorial?。 不要忘记在您的 settings.py 文件中设置 TEMPLATE_DIRS ,可以在另一个答案中找到这样做的好技巧; Django template Path

      【讨论】:

        【解决方案3】:

        在您的项目 settings.py 文件中:

        在顶部添加这个

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

        然后设置模板路径这样做:

        TEMPLATE_DIRS = (
            os.path.join(PROJECT_ROOT, "templates"),
        )
        

        【讨论】:

          【解决方案4】:

          有了这个,你将来有义务重新检查你的所有文件以更改路径,以防你改变目录:在你settings.py文件定义:

          import os.path
          
          TEMPLATE_DIRS = (
           os.path.join(os.path.dirname(__file__),'templates').replace('\\','/'),
           '/path/to/my/project/'
           '/path/to/my/project/template/', # for the apps
          )
          

          templates/ 是您的模板的目录。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2016-12-19
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-10-14
            • 2014-08-26
            • 2012-05-17
            • 2019-04-10
            相关资源
            最近更新 更多