好吧,我不知道该问题应如何称呼,但我想知道网站例如一点点地工作。
我的意思是-缩短链接时会得到结果:
def upload_to(instance, filename):
return 'uploads/{id}/{fn}'.format(id=instance.pk,fn=filename)
class Mechanism(models.Model):
"""
A chemical kinetic mechanism, from Chemkin or Cantera
"""
ck_mechanism_file = models.FileField(upload_to=upload_to, max_length=100, blank=True, null=True,
verbose_name="Chemkin mechanism file")
ck_thermo_file = models.FileField(upload_to=upload_to, max_length=100, blank=True, null=True,
verbose_name="Chemkin thermo file")
ck_transport_file = models.FileField(upload_to=upload_to, max_length=100, blank=True, null=True,
verbose_name="Chemkin transport file")
ck_surface_file = models.FileField(upload_to=upload_to, max_length=100, blank=True, null=True,
verbose_name="Chemkin surface file")
ct_mechanism_file = models.FileField(upload_to=upload_to, max_length=100, blank=True, null=True,
verbose_name='Cantera yaml file')
ct_conversion_errors = models.TextField(verbose_name='Errors from the ck2yaml conversion')
timestamps = models.DateTimeField(auto_now_add=True)
我知道如何获得类似
class MechanismObjectMixin(object):
model = Mechanism
def get_object(self):
pk = self.kwargs.get('pk')
obj = None
if pk is not None:
obj = get_object_or_404(self.model, pk=pk)
return obj
class MechanismUpdateView(MechanismObjectMixin, View):
template_name="file_update.html"
def get(self, request, id=id, *args, **kwargs):
context = {}
obj = self.get_object()
if obj is not None:
form = ChemkinUpload(instance=obj)
context['object'] = obj
context['form'] = form
return render(request, self.template_name, context)
def post(self, request, *args, **kwargs):
obj = self.get_object()
form = ChemkinUpload(request.POST, request.FILES, instance=obj)
if form.is_valid():
form.save()
url = reverse_lazy('mechanism-detail', args=[obj.pk])
return HttpResponseRedirect(url)
(GET方法)的效果,但是我不知道如何获得上述效果。
答案 0 :(得分:0)
您基本上可以通过以下两种方式执行此操作:
带有mod_rewrite的.htaccess路由
在您的根文件夹中添加一个名为.htaccess
的文件,并添加如下内容:
RewriteEngine on
RewriteRule ^/?Some-text-goes-here/([0-9]+)$ /picture.php?id=$1
这将告诉Apache为该文件夹启用mod_rewrite,如果询问它与正则表达式匹配的URL,它将在内部将其重写为所需内容,而最终用户看不到它。简单但不灵活,因此,如果您需要更多功能,则:
PHP路线
请在.htaccess文件中放置以下内容:(注意斜杠)
FallbackResource /index.php
这将告诉它为通常在您的站点中找不到的所有文件运行index.php。然后,您可以在其中例如:
$path = ltrim($_SERVER['REQUEST_URI'], '/'); // Trim leading slash(es)
$elements = explode('/', $path); // Split path on slashes
if(empty($elements[0])) { // No path elements means home
ShowHomepage();
} else switch(array_shift($elements)) // Pop off first item and switch
{
case 'Some-text-goes-here':
ShowPicture($elements); // passes rest of parameters to internal function
break;
case 'more':
...
default:
header('HTTP/1.1 404 Not Found');
Show404Error();
}
这是大型站点和CMS系统执行此操作的方式,因为它在解析URL,配置和数据库相关的URL等方面提供了更大的灵活性。对于零星使用,.htaccess
中的硬编码重写规则可以很好地解决问题。