【发布时间】:2021-04-23 12:23:05
【问题描述】:
我正在使用 html 模板上传文件,但我不知道如何在 django 视图文件中处理该文件 我也有一个与数据库连接的模型
这是我的 html 文件
{% extends 'base.html' %}
{% block body %}
<form action="file" method="post" enctype="multipart/form-data" >
{% csrf_token %}
<input type="text" name="userName" placeholder="username">
<input name="file" type="file">
<input type="submit" value="submit">
</form>
{% for message in messages %}
{{ message }}
{%endfor%}
{% endblock %}
这是我的views.py函数
def File(request):
if request.user.is_authenticated:
if request.method == 'POST':
user = request.POST['userName']
file = request.FILES
print(file)
# file = request.POST.copy()
# file.update(request.FILES)
# content_type = copied_data['file'].get('content-type')
# path = os.path.join(r'C:\Users\harsh\PycharmProjects\swatchBharat\SwatchBharat\media\files\\',file)
if User.objects.filter(username=user).exists():
file2 = points()
file_obj1 = DjangoFile(open(file, mode='rb'), name=file)
file_obj = File.objects.create(title=file, file=file_obj1, content_object=file, author=file.client)
file2.file =file2.save(ContentFile(file_obj))
file2.user = user
file2.save()
return HttpResponse('sucess bale bale!!!!!!!')
else:
messages.info(request,'the username you entered is incorrect')
return redirect("file")
return render(request, 'file.html')
else:
return HttpResponse('sorry this is restricted, login to continue')
我的 model.py 文件
from django.db import models
# Create your models here.
class points(models.Model):
user = models.TextField(max_length=50,default=None)
file = models.FileField(upload_to='files/')
point_3 = models.BooleanField(default=False)
point_5 = models.BooleanField(default=False)
point_9 = models.BooleanField(default=False)
我被它困住了,请有人帮助我
【问题讨论】:
-
你可以通过这个文档来做。可能会有所帮助。 docs.djangoproject.com/en/3.2/topics/http/file-uploads
-
卡住是什么意思?你没有回答一个问题。只是说“我被卡住了”并没有帮助。请更具体。你在哪里卡住了?
-
我被卡住了,这意味着我尝试了许多关于 * 的解决方案,但没有奏效,您可以在代码中将其视为 cmets
-
从表单输入的文件是图像和视频
-
我想将它们添加到我的模型对象文件字段中,该字段应该上传到我的目标目录和数据库,但它作为错误“文件”对象没有属性“_committed”而出现,有时错误,它需要字节类型输入,但我提供多数据
标签: html python-3.x django