Skip to main content
 首页 » 编程设计

python之Django 多张上传图片不起作用

2025年04月02日39jpfss

我正在尝试添加多张上传,但在我上传 2 张或更多图片的地方只能添加一张 添加文件的 View :

def post_new(request): 
if request.method == "POST": 
    form = PostForm(request.POST, request.FILES) 
    if form.is_valid(): 
        try: 
            f = request.FILES['image'] 
            post = form.save(commit=False) 
            post.image.save(f.name, f) 
            post.date = timezone.now() 
            post.save() 
        except MultiValueDictKeyError: 
            post = form.save(commit=False) 
            post.date = timezone.now() 
            post.save() 
        return redirect('home:index') 
    else: 
        form = PostForm() 
    return render(request, 'home/edit_post.html', 
                  {'form': form, 'error_message': 'something error message'}) 
else: 
    form = PostForm() 
return render(request, 'home/edit_post.html', {'form': form}) 

以及我获取图像形式的形式:

class PostForm(forms.ModelForm): 
 
class Meta: 
    model = Post 
    fields = ['title', 'text', 'image'] 

我也试过这个:

image = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) 

但这并没有帮助

自己的模型图片在哪里:

class Post(models.Model): 
title = models.CharField() 
date = models.DateTimeField(editable=True, null=True) 
text = models.TextField() 
image = models.ImageField(null=True, blank=True, upload_to='my-images') 
is_super = models.IntegerField(default=0) 

模板 edit_post:

<form action="" method="POST" enctype="multipart/form-data">{% csrf_token %} 
    {% if error_message %} 
        <p><strong style="margin-left: 35%; color: red">{{ error_message }}</strong></p> 
    {% endif %} 
    <div class="input-group" style="margin-bottom: 10px; margin-left: 38.5%"> 
        <label for="id_title" style="margin-left: 35%">title</label> 
        <input style="text-align: center" value="{{ form.title.value }}" class="form-control" placeholder="****" id="id_title" name="title" type="text"> 
    </div> 
    <div class="input-group" style="margin-bottom: 10px; margin-left: 30%"> 
        <label for="id_text" style="margin-left: 42%">text</label> 
        <textarea style="resize: none; width: 500px; height: 250px" placeholder="***" class="form-control" id="id_text" name="text">{{ form.text.value }}</textarea> 
    </div> 
    <div class="input-group" style="margin-bottom: 10px; margin-left: 40%"> 
{{ form.image }} 
    </div> 
    <button type="submit" class="save btn btn-default" style="margin-left: 45.2%; margin-bottom: 20px">edit</button> 
</form> 

我很乐意提供任何帮助

请您参考如下方法:

您的 Post 模型只有一个图像字段,那么您会如何处理其他图像?如果你希望每个帖子有零个、一个或更多张图片,你需要一个独特的Image模型,在Post上有一个外键,然后使用Formset对于图像