gpt4 book ai didi

html - 使用 ModelForms 在 Django 中上传文件

转载 作者:搜寻专家 更新时间:2023-10-31 23:07:21 25 4
gpt4 key购买 nike

我已经在这个项目上花费了好几个小时,只是想不出如何创建一个简单的文件上传应用程序。我已经查看了所有教程,但没有一个完全适用于我的情况,而且我无法正确编写代码。我知道此时我拥有的代码不会运行,但我希望有人能够用我拥有的东西将我推向正确的方向。我知道它不是很好,但我很沮丧,我希望有人能帮助我,特别是我的 views.py 非常感谢。先感谢您!

模型.py

from django.db import models
from django.contrib.auth.models import User
from django.forms import ModelForm


class WorkSheet(models.Model):
worksheet_name = models.CharField(max_length= 150, default = True)
creator = models.ForeignKey(User, default = True)
worksheet_file = models.FileField(upload_to = 'worksheets', default = True)
number_of_stars = models.PositiveIntegerField(default = True)
category = models.CharField(max_length = 100, default = 0)


class UploadWorkSheetForm(ModelForm):
class Meta:
model = WorkSheet

Views.py

from django.shortcuts import render, render_to_response, HttpResponseRedirect
from django.conf import settings
from django import http


from models import WorkSheet
from forms import UploadWorkSheetForm

def upload(request):
template = 'upload.html'
if request.method == 'POST':
if 'file' in request.FILES:
file = request.FILES['file']
filename = file['filename']
fd = open('%s/%s' % (settings.MEDIA_ROOT, filename), 'wb')
fd.write(file['content'])
fd.close()

return http.HttpResponseRedirect('upload_success.html')
else:
form = UploadWorkSheetForm()
return render_to_response(template, {'form': form})

return render(request, 'upload.html', {'form': form})

Upload.html

<!DOCTYPE html>
<html>
<head>
<title>WSD Upload</title>
</head>
<body>
<h1>Upload WorkSheet</h1>
{% block body %}
<form action="." method="post" enctype="multipart/form-data"> {{ form }}
<type="submit" value = "Upload"/>
</form>
{% endblock %}
</body>
</html>

如果您还有什么需要请告诉我。谢谢谢谢谢谢!

最佳答案

View .py

def upload(request):
template = 'upload.html'
if request.method == 'POST':
form = UploadWorkSheetForm(request.POST, request.FILES)
if form.is_valid():
form.save()

return HttpResponseRedirect('upload_success.html') <---change this to your valid url not template name
else:
form = UploadWorkSheetForm()

return render(request, 'upload.html', {'form': form})

模板

...................        
{% block body %}
<form action="." method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value = "Upload"/>
</form>
{% endblock %}
....................

关于html - 使用 ModelForms 在 Django 中上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15846120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com