python - 为特定用户保存 .docx 文件 django
问题描述
我正在用 django 中的用户输入创建一个 docx 文件。现在,当单击提交按钮时,会生成下载链接,用户可以下载文件。但是我想将文件保存在文件存储中并创建一个模板,用户可以在其中看到他过去创建的所有 docx 文件(或超链接)。“有点像数据库”
模型.py
class Timetables(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,
default=1, related_name='timetables_files', null=True)
timetable_files = models.FileField(
null=True, blank=True, upload_to='word_documents')
视图.py
def school_view(request):
if request.method == 'POST':
worddocument = docx.Document()
documenttitle = worddocument.add_heading(
school_name_view.title(), 0)
file = io.BytesIO()
worddocument.save(file)
response = HttpResponse(
content_type='application/vnd.openxmlformats-
officedocument.wordprocessingml.document')
response['Content-Disposition'] = 'attachment; filename =quicktimetable.docx'
worddocument.save(response)
path = join(settings.MEDIA_ROOT, 'word_documents',
'quicktimetable.
file = open(path, 'w+b')
return response
class TimetablesView(ListView):
model = Timetables
template_name = 'quickmain/timetables_list.html'
时间表列表.html
{% if user.is_authenticated %}
{% for f in files %}
{{ f.files.url }}
{% endfor %}
{% for timetable_files in user.timetables_files.all %}
<embed src = "{{timetable_files.timetable_files.url}}" target="__blank">
{% endfor %}
{% else %}
如何保存生成的文件并在不同的模板上显示与该用户相关的所有文件。我的 models.py 中有一个 FileField,但不知道如何使用它。每当用户要求时,我都会建议重新生成文件,但我也不知道。
解决方案
您必须创建文件和用户模型之间的关系。模型中的示例
class DocxFile(models.Model):
user = models.ForiegnKey(User) #your user model name
file = models.FileField('upload_to='/')
那么在你看来
from yourappname.models import DocxFile
def docs_file(request):
files = DocxFile.object.filter(user=request.user)
return render('your template path', {'files':files})
在您的模板中
{% for f in files%}
{{f.file.url}}
{% endfor %}
推荐阅读
- c++ - 在 Visual Studio 2017 中使用库设置 vc++ 项目的正确方法
- c++ - C++ - 为什么是 std::function
无效的? - python - Python - ConnectionRefusedError、urllib3.exceptions.NewConnectionError 和 Colorama
- python - dlib-build@0.1.1 安装失败
- c++ - string to double 或 float 截断小数点
- php - .htaccess 重写会留下损坏的图像
- python - PyQt4:如何使文件对话框弹出并停留?
- c# - 密封类的类实例化的依赖注入
- javascript - 如何在后台获取 YouTube 网址?
- c-strings - 为什么我必须在 C++ 中包含 .c_str() 来查找字符串长度?