【发布时间】:2021-10-11 22:52:31
【问题描述】:
在我的例子中,用户在前端输入一个词,在后端,我将调用我编写的一些函数,最后,我将在/media/reports 目录中构建一个 .PDF 文件.
如何使这些文件特定于用户并将它们保存在数据库中?
在此之前,我实现了没有模型和表单的代码,只是将文件保存在/media/reports/ 目录中。并且用户可以在被重定向到下载页面后立即下载该文件。
但是现在,我想将这些文件保存到数据库中,以便每个用户都可以访问其个人资料中的新文件。我该怎么做?
这是我的代码:
views.py:
@login_required(login_url='/login/')
def dothat(request):
if request.method == 'GET':
return render(request, 'app/dothat.html')
else:
try:
global word, user_name, function_name
function_name = dothat.__name__
word = request.POST.get("word")
user_name = request.user
full_name = request.user.get_full_name()
myscript.script_one(word, user_name,full_name, function_name)
# And in the called myscript, after doing some things,
# the PDF file will be saved in /media/reports/ directory
except ValueError:
return render(request, 'app/dashboard.html', {'error':'Bad data passed in. Try again.'})
# And then, the user will be redirected to the download page to download that single file
return render(request, 'app/download.html')
还有views.py中的download_file函数
@login_required(login_url='/login/')
def download_file(request):
filename = f"{function_name}-{word}.pdf"
# Define the full file path
filepath = f"{BASE_DIR}/app/media/app/reports/{user_name}/{filename}"
# Open the file for reading content
if os.path.exists(filepath):
# Set the return value of the HttpResponse
response = HttpResponse(open(filepath, 'rb'))
# Set the HTTP header for sending to browser
response['Content-Disposition'] = "attachment; filename=%s" % filename
return response
# Return the response value
else:
raise HTTP404
这里是models.py,这是基于我的新需求,我不确定它是否正确:
from django.db import models
from django.contrib.auth.models import User
class Report(models.Model):
word = models.CharField(max_length=100)
title = models.CharField(max_length=100) # i want this title be the file name that i built in the dothat() function.
report_file = models.FileField(upload_to='reports/%Y/%m/%d')
report_date = models.DateTimeField(auto_now=True)
owner = models.ForeignKey(User, on_delete = models.CASCADE)
forms.py
from django.forms import ModelForm
from .models import Report
from django import forms
class IpscanForm(ModelForm):
class Meta:
model = Report
fields = ['word'] # user just enter the word
我想在表单和模型中实现用户单一输入,将在后端处理的文件保存在数据库中,并收集所有用户特定的文件以在下载部分页面上显示给用户。我只是不知道如何将这些东西联系在一起。你有什么想法可以帮到我吗?
【问题讨论】:
-
嘿,只是想澄清一下,您是在问如何查询特定用户的所有报告并将其显示在他的个人资料中,对吗?
-
@Girik1105 是的。在当前情况下,我没有在数据库中保存任何内容。我只是将文件保存(写入)用户当时可以访问的目录中的最后一个报告。我想添加这个选项:每个用户都可以看到他的报告。
-
您可以使用将用户的pk与报告一起保存的模型,以便他或她可以访问他或她的报告。您之前刚刚写入数据库的报告无法查询,因为我们没有关于谁发布它们的数据。我应该编写代码来了解如何查询一个人的个人资料报告吗?
-
@Girik1105 谢谢。我写了我所知道的一切(我发布了我的 model.py 和我的 forms.py 尚未实现。)但我不知道如何在这种情况下使用它们。如果可以的话,请多帮我写代码
-
你是使用 django-rest-framework 还是只使用 django?
标签: python-3.x django django-models django-forms