我正在使用Django创建一个Webapp。当用户按下某个按钮时,它需要将文件路径作为参数和字符串参数传递给我的一个视图。我不能简单地在URL中使用参数,因为该路径包含多个'/'。我现在设置的方式如下:
parameters.py
class FilePathConverter:
regex = '^[/]'
def to_python(self, value):
value=str(value)
return value.replace("?", "/")
def to_url(self, value):
value=str(value)
return value.replace("/", "?")
urls.py
from django.urls import path
from . import views
from django.contrib import admin
from django.views import generic
from django.urls import path, register_converter
from . import converters, views
register_converter(converters.FilePathConverter, 'filepath')
urlpatterns = [
path('', views.index, name='webpanel-index'),
path('controlserver/<filepath:server_path>/<str:control>', views.index, name='controlserver'),
]
views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Server
from django.contrib.auth.decorators import login_required
import subprocess
def controlserver(request, server_path, control):
if request.POST:
subprocess.call(['bash', server_path, control])
return render(request, 'index.html')
但是,使用这种方法,我会收到此错误:
Reverse for 'controlserver' with keyword arguments '{'server_path': 'rien/', 'control': 'start'}' not found. 1 pattern(s) tried: ['controlserver/(?P<server_path>[^/]+)/(?P<control>[^/]+)$']
答案 0 :(得分:1)
您可以使用Slug通过以下方式解决此模式:
从django.utils.text导入slugify
但是您需要在视图和模板中添加slug,因此请检查以下slug和pk列表:
https://github.com/salah-cpu/migration/blob/master/PATH_slug_pk