我必须在我的django网址中用模拟在url中写一个正则表达式,文件的路径是什么?哪里有“目录”,“子目录”和“文件”,每个对象的模型都有“slug”。
我已经这样做了:
model.py
class Directory(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(max_length=100, unique=True,)
subdirectory = models.ForeignKey('self', null=True, blank=True)
class File(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(max_length=100, unique=True,)
directory = models.ForeignKey(Directory)
views.py
class DirectoryView(generic.DetailView):
model = Directory
template_name = 'appname/directory.html'
class FileView(generic.DetailView):
model = File
template_name = 'appname/file.html'
应用程序名称/ urls.py
urlpatterns = [
url(r'^(?P<slug>[-\w]+)/$',
views.DirectoryView.as_view(), name='directory'),
url(r'^(?P<slug1>[-\w]+)/(?P<slug>[-\w]+)/$',
views.FileView.as_view(), name='file'),
]
“file1.txt”的结果网址是:
的http:/mydomain.com/appname/subfolder1/file1txt
但我需要它:
的http:/mydomain.com/appname/的文件夹2 / subfolder1 / file1txt
谢谢,
伊万
答案 0 :(得分:0)
所以我终于在这个django片段中找到了答案:
https://djangosnippets.org/snippets/362/
这就是我最后得到的结果:
<强> models.py 强>
class Directory(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(max_length=100, unique=True,)
parent = models.ForeignKey('self', null=True, blank=True)
def get_absolute_url(self):
url = "/%s/" % self.slug
cwd = self
while cwd.parent:
url = "/%s%s" % (cwd.parent.slug, url)
cwd = cwd.parent
return url
class File(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(max_length=100, unique=True,)
directory = models.ForeignKey(Directory)
<强> views.py 强>
from django.http import Http404
from django.shortcuts import render, get_object_or_404
from .models import Archive, Directory, File
def directories(request, full_slug):
slugs = full_slug.split('/')
cwd_slug = slugs[-1]
directory = get_object_or_404(Directory, slug=cwd_slug)
if not directory.get_absolute_url().strip('/') == full_slug:
raise Http404
# if you reach this line, you've found the directory
context = {'directory': directory}
template = 'appname/directory.html'
return render(request, template, context)
def files(request, full_slug, file_slug):
slugs = full_slug.split('/')
cwd_slug = slugs[-1]
directory = get_object_or_404(Directory, slug=cwd_slug)
if not directory.get_absolute_url().strip('/') == full_slug:
raise Http404
files = get_object_or_404(File, name=file_slug)
# if you reach this line, you've found the file
context = {'archive': archive_slug, 'directory': full_slug, 'file': files}
template = 'getdocs/file.html'
return render(request, template, context)
<强>应用程序名称/ urls.py 强>
from django.conf.urls import url, include
from . import views
file_patterns = [
url(r'^$', views.directories, name='directory'),
url(r'^(?P<file_slug>(.*)[.]{1}[-\w]{3})$', views.files, name='file'),
]
urlpatterns = [
url(r'^(?P<full_slug>(.*))/', include(file_patterns)),
]
我希望这有助于其他人。