python - 我想使用 django 中的默认形式将图像上传到数据库,但图像未上传。它显示 "No file chosen"

标签 python html django

forms.py

from django import forms
from .models import Posts


class PostForm(forms.ModelForm):
    class Meta:
        model = Posts
        fields = ['topic','post','thumbnail','author']

models.py

class Posts(models.Model):
topic = models.ForeignKey(Topic,on_delete=models.CASCADE)
post = models.TextField()
date = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(Author,on_delete=models.CASCADE)
thumbnail = models.ImageField()

def __str__(self):
    return f"{self.post[:20]}..."

class Meta:
    verbose_name_plural = 'posts'

views.py

def add_post(request):
if request.method == 'POST':
    form = PostForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect("/")
else:
    form=PostForm()
context = {'form':form}
return render(request,'blog/add_post.html',context)

add_post.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <form action="{% url 'blog:add_post' %}" method='post'>
    {% csrf_token %}
    {{form.as_p}}

    <input type='submit'>
    </form>
</body>
</html>

当我尝试提交表单时,即使我选择了文件,缩略图字段也会自动显示“未选择文件”。所以请帮我解决这个问题! when i try to submit it shows "No file chosen" even when i chose

最佳答案

您必须添加 upload_to:

    item_image = models.ImageField(
        blank = True,
        null = True,
        upload_to = 'item/image/',
        db_column = 'ITEM_IMAGE',
        verbose_name = 'IMAGE',
    )

记住分配媒体文件的路径:(在settings.py上)

MEDIA_URL = '/media/' 
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') 

在 forms.py 中:

    item_image = forms.ImageField(
        required = False,
        label = 'Image',
        widget = forms.ClearableFileInput(
            attrs = {'class': 'form-control mb-2', 'placeholder': 
        'IMAGE',}
        ),
    )

这是我的 github,其中有一个 django 项目可以指导您:

Github/Django

关于python - 我想使用 django 中的默认形式将图像上传到数据库,但图像未上传。它显示 "No file chosen",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59841869/

相关文章:

Python:使用基于嵌套列表中唯一值的列创建 Pandas 数据框

python - 在 Jupyter Notebook 中导入模块 - 路径

html/css定位三个文本框

html - Bootstrap : Custom CSS not working on button hover

django.db.utils.ProgrammingError : Could not load : column "" of relation "" does not exist

python - 在附加条件下与 pd.NamedAgg 聚合

python - numpy 分块矩阵如何工作?

html - 为什么内部DIV会溢出外部DIV?

python - 导入错误: No module named 'django' uWSGI Django Nginx Ubuntu 16. 04 Python3.6

django - Django select_for_update不能在事务外部使用