Django表单未将多个图像保存到数据库

时间:2020-06-10 10:49:51

标签: django django-models django-forms django-views

我正在学习django。我的django表单即使选择了多个图像,也只能将单个图像保存到数据库中。任何帮助将不胜感激。这是我的代码;

models.py

class Post(models.Model):
    post = models.TextField(max_length=500, null=False, blank=False)
    image = models.ImageField(blank=True)
    date_published = models.DateTimeField(auto_now=True, verbose_name='date published')
    date_updated = models.DateTimeField(auto_now=True, verbose_name='date updated')
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    slug = models.SlugField(blank=True, unique=True)

    def __str__(self):
        return self.detail


@receiver(post_delete, sender=Post)
def submission_delete(sender, instance, **kwargs):
    instance.image.delete(False)


def pre_save_ad_post_receiver(sender, instance, *args, **kwargs):
    if not instance.slug:
        instance.slug = slugify(instance.author.username + '-' + instance.detail)


pre_save.connect(pre_save_ad_post_receiver, sender=Post)

forms.py

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

    class Meta:
        model = Post
        fields = [ 'post', 'image']

观看次数

def home(request):
    context = {}
    form = CreatePostForm(request.POST or None, request.FILES or None)
    images = request.FILES.getlist('images')
    if form.is_valid():
        for img in images:
            Post.objects.create(image=img)
        obj = form.save(commit=False)
        obj.author = user
        obj.save()
        form = CreatePostForm()

    context['post_form'] = form

    return render(request, 'posts/home.html', context)

0 个答案:

没有答案