Django在formset上进行表单验证-上传多张图片

时间:2019-06-30 19:23:12

标签: django python-3.x

我从我的视图中获取请求数据,但是无法从表单中验证我的数据,我尝试了很多不同的事情,我想使用表单集多次上载图像。任何帮助表示赞赏!

我只有一个图像字段,并且在我的模型中引用了我的Post模型。 我的表格仅包含我的图像字段。

images <MultiValueDict: {'files[]': [<TemporaryUploadedFile: Screenshot 2019-06-18 at 18.11.47.png (image/png)>, <TemporaryUploadedFile: touch.of.boho-white-home-about_seeking_and_finding.jpg (image/jpeg)>, <TemporaryUploadedFile: Screenshot 2019-06-18 at 19.38.40.png (image/png)>, <TemporaryUploadedFile: touch.of.boho-white-home-about_seeking_and_finding -boheme-lifestyle.jpg (image/jpeg)>]}>

Model.py

    from django.db import models
    from blog.models import Post

    class Catalog_images(models.Model):
        post = models.ForeignKey(Post, on_delete=models.CASCADE)
        image = models.ImageField(upload_to='catalog/', blank=True,null=True)
        #title = models.TextField(max_length=255, null=True, blank=True)

        def __str__(self):
            return self.post.title + " Image"

Forms.py

 class ImageUploadForm(forms.ModelForm):
            image = forms.ImageField(label='image')
            class Meta:
                model = Catalog_images
                fields = ('image',)

Views.py

   def catalog_upload_view(request):
    template_name = 'utils/catalog-upload.html'
    ImageFormset = modelformset_factory(Catalog_images, fields=('image',), extra=4)
    #ImageFormset = modelformset_factory(Catalog_images, form=ImageUploadForm, extra=4)
    if request.method == 'POST':
        print(request.POST)
        image_form = ImageUploadForm(request.POST)
        formset = ImageFormset(request.POST or None, request.FILES or None, queryset=Catalog_images.objects.none())
        print('images', request.FILES)

        if image_form.is_valid() and formset.is_valid():
            print('form is valid')
            post = image_form.save(commit=False)
            post.user = request.user
            post.save()

            for f in formset:
                print(f)
                try:
                    photo = Catalog_images(post=post, image=f.cleaned_data['image'])
                    print(photo)
                    photo.save()
                    messages.success(request, 'You Successfully uploaded to MYNORDICROOM')
                except Exception as e:
                    break
        else:
            print('form not valid')
            print(image_form._errors)

    else:
        image_form = ImageUploadForm()
        formset = ImageFormset(queryset=Catalog_images.objects.none())
    context = {
        'form': image_form,
        'formset': formset,
    }
    return render(request, template_name, context)

HTML:

<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    {{ formset.as_table }}
    <div class="drop">
        <div class="cont">
            <i class="fa fa-cloud-upload"></i>
            <div class="tit">
                Drag & Drop
            </div>
            <div class="desc">
                Your Interior Design Collection of Images
            </div>
            <div class="browse">
                click here to browse
            </div>
        </div>
        <output id="list"></output>
        <input id="files" multiple="true" name="files[]" type="file" onchange="this.form.submit()" />
    </div>
</form>

0 个答案:

没有答案