如何在Djnago CreateView中上传多个图像?

问题描述 投票:0回答:1

我有一个django项目,我在该项目中创建了一个后期操作,因此用户将可以共享多个图片。但是我有一个问题。我无法编写多张图片上传功能。我看了很多内容,但是没有用。它报告了一个问题,或者contex没有发送到我想要的html页面。请帮我。我想要的多图片功能应该在CreateView下,并且应该与它放在同一模板中。另外,应该有4个图片上传按钮,最后一个应该分配多个功能(到html标签)

models.py:

class Photo(models.Model):
post= models.ForeignKey(Person, on_delete=models.CASCADE)

image = models.ImageField(upload_to=get_image_filename)
uploaded_at = models.DateTimeField(auto_now_add=True)

views.py:

class PersonCreateView(CreateView):
model = Person
form_class = PersonForm
success_url = reverse_lazy('person_changelist')

forms.py:

    class PhotoForm(forms.ModelForm):
    image = forms.ImageField(label='Image')
    class Meta:
        model = Photo
        fields = ('image', )


class PersonForm(forms.ModelForm):
    title = forms.CharField(max_length=128)
    body = forms.CharField(max_length=245, label="Item Description.")
    file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))

    class Meta:
        model = Person
        widgets = {
            'valyuta': forms.RadioSelect,
            'barter': forms.CheckboxInput,

        }
        fields = ('country', 'city', 'ban', 'yurus', 'reng', 'qiymet', 'valyuta', 'yanacaqnovu', 'oturucu', 'squtu', 'buraxilisili', 'hecm', 'seher', 'barter', 'metin')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['city'].queryset = City.objects.none()


        if 'country' in self.data:
            try:
                country_id = int(self.data.get('country'))
                self.fields['city'].queryset = City.objects.filter(country_id=country_id).order_by('name')
            except (ValueError, TypeError):
                pass  # invalid input from the client; ignore and fallback to empty City queryset
        elif self.instance.pk:
            self.fields['city'].queryset = self.instance.country.city_set.order_by('name')
python django django-models image-uploading create-view
1个回答
0
投票

看看是否可行。创建一个简单的HTML表单而不是Django的模型表单

<form enctype="multipart/form-data" action="" method="post">
    <input type="file" name="uploaded_images" accept="image/*" multiple>
    <input type="submit" name="upload" value="Upload">
</form>

您认为:

if request.method == 'POST':
    for afile in request.FILES.getlist('uploaded_images'):
        #Save images in respective models with the links to other models
        return redirect('back/to/same/url')

这将使用户能够一次上传多张图像,并且您将能够轻松处理单个图像。

© www.soinside.com 2019 - 2024. All rights reserved.