提问人:maria 提问时间:7/19/2023 最后编辑:maria 更新时间:7/19/2023 访问量:35
图像文件未上传到媒体文件 [重复]
Image file not being uploaded to media file [duplicate]
问:
我正在尝试显示接受图像文件的输入 type=“file”。当我通过 Django Admin 上传文件时,一切正常(它上传到我的媒体文件夹,并成功显示在 html 上),但是当我通过我的 html 页面上传文件时,它不会转到媒体,我无法显示它。所以我假设问题不在于 django,而在于我的 settings.py 或我的 html
帮助
创建 .html (上传图像)
<label for="imgpreview" class="imglabel">Choose Image</label>
<input accept="image/*" type='file' id="imgpreview" name="imgpreview" class="image-form" onchange="previewImage(event);"/>
索引:.html(显示图像)
<div class="banner-image"><img id="model-img-display" src="{{item.image.url}}"></div>
views.py(保存模型)
def create(request):
if request.method == 'POST':
title = request.POST['title']
image = request.POST['imgpreview']
category = request.POST['category']
brand = request.POST['brand']
color = request.POST['color']
clothes = Clothes(title=title, image=image, category=category, brand=brand, color=color)
clothes.save()
return render(request, "wardrobe/create.html")
models.py
class Clothes(models.Model):
title = models.CharField(max_length=50)
image = models.ImageField(default='', upload_to='wardrobe/') #wardrobe= media subfolder
category = models.CharField(max_length=200, null=True, blank=True)
brand = models.CharField(max_length=200, null=True, blank=True)
color = models.CharField(max_length=200, null=True, blank=True)
deleted = models.BooleanField(default=False)
settings.py
MEDIA_URL='/media/'
MEDIA_ROOT= BASE_DIR/'project5'/'wardrobe'/'media'
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('wardrobe.urls')),
] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
编辑:我按照 https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html 说明更改了我的 views.py,现在一切正常!
答:
1赞
Gin Fuyou
7/19/2023
#1
您没有使用 () 处理您的输入,这是巨大的反模式,也是您问题的间接来源之一。forms.Form
ModelForm
- 为模型定义一个类(管理员正在使用一个类)
ModelForm
form = ClothesForm(request.POST, request.FILES) # files are not part of POST
- 确保 html 标签具有正确的属性来发送二进制数据,否则您将看不到正在发送的文件。
<form>
enctype
像好的教程一样处理表单验证和处理。DjangoGirls 在表单上有一个很好的。
评论