3 回答
TA贡献1812条经验 获得超5个赞
你可以这样做:view.py
from django.views.generic import TemplateView
class PageView(TemplateView):
def get_template_names(self):
template_name = "path_to_template/{}.html".format(self.kwargs["page_name"])
return [template_name]
然后将更改添加到您的 urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('pages/<page_name>/', views.PageView.as_view()),
path('', views.home_page),
]
TA贡献2011条经验 获得超2个赞
您可以有一个单独的模型来存储生成的 HTML 的路径,就像这样
class HTMLGenerated(models.Model):
name = models.CharField(max_length=100)
path = models.CharField(max_length=500) # This will store the relative path
然后您可以在 URL 模式中使用 URL 参数,如下所示:
urlpatterns = [
path('admin/', admin.site.urls),
path('<int:html_id>/reports/', views.report_view)
]
相应的视图可以处理类似的东西:
def report_view(request, html_id):
object = get_object_or_404(HTMLGenerated, pk=html_id)
# You can access the HTML by
html = object.path
# Return the context
return render(
request,
'some_template',
context = {
'html': html
}
TA贡献1828条经验 获得超6个赞
从评论移动到这里进行代码格式化,请您进一步指导和纠正我。谢谢堆。
这是更新的 urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('pages/<page_name>/', views.PageView.as_view()),
path('', views.welcome_page, name='welcome_page'),
path('results/', views.andreys_generate_results_file, name='andrey_script')
]
这是 views.py 代码
class PageView(TemplateView):
def get_template_names(self):
template_name = "templates/{}.html".format(self.kwargs["page_name"])
return [template_name]
def andreys_generate_results_file(request):
hhmmss = str(datetime.now().strftime("%H%M%S"))
yyyymmdd = str(datetime.now().strftime("%Y%m%d"))
# new_file_name = yyyymmdd + "/results_" + hhmmss + ".html" # actual line, commented for Andrey
new_file_name = "templates/results_" + hhmmss + ".html"
ls_cmd = "pwd; ls -lart | tee " + new_file_name
output = subprocess.Popen(ls_cmd, shell=True, stdout=subprocess.PIPE)
wait_for_sec = request.POST.get('seconds')
time.sleep(int(wait_for_sec))
return render(request, new_file_name)
def welcome_page(request):
# Purpose: Just display welcome_page.html
return render(request, 'welcome/welcome_page.html')
这是 welcome_page.html 表单代码的一部分:
<p>New Form</p>
<hr>
<form action="{% url 'andrey_script' %}" method="post">
{% csrf_token %}
Text:
<input type="text" name="seconds" required><br><br>
<button type="submit" value="Run Python Script"> Click to Run Python Script</button>
</form>
添加回答
举报