如何将多个图像上传到django中的博客文章 [英] how to upload multiple images to a blog post in django

查看:184
本文介绍了如何将多个图像上传到django中的博客文章的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试允许每个用户将多张照片上传到一个博客文章。我一直试图找出最好的方法来做这几天。这样做最好的做法是什么?

I am trying to allow each user to upload multiple pictures to a single blog post. I have been trying to work out the best way to do this for a few days now. What is the best practice to do this?

从我所看到的,我应该从博客模型中创建一个独立的图像模型,并使用外键。是对的吗?
那么有什么事情可以让他们同时上传多张照片。我假设我应该使用放置区域吗?

From what I have read, I should make a seperate image model from the blog post model and use a foreign key. Is that right? Then there is the matter of how to allow them to upload multiple pictures at the same time. Am I right in assuming I should use something like drop zone?

任何关于存储照片的最佳做法的建议也是受欢迎的。我看过亚马逊的s3和云。我想创建一个可扩展的东西。

Any advice on best practices for storing the photos is also welcome. I have looked at Amazon s3 and cloudinary. I want to create something which is scalable.

任何帮助将不胜感激!

推荐答案

你只需要两个模型。一个为邮政和另一个将为图像。您的图像模型将具有邮政模型的外键:

You'll just need two models. One for the Post and the other would be for the Images. Your image model would have a foreignkey to the Post model:

class Post(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=128)
    body = models.CharField(max_length=400)

def get_image_filename(instance, filename):
    title = instance.post.title
    slug = slugify(title)
    return "post_images/%s-%s" % (slug, filename)  



class Images(models.Model):
    post = models.ForeignKey(Post, default=None)
    image = models.ImageField(upload_to=get_image_filename,
                              verbose_name='Image', )

您需要为每个模型创建一个表单,但它们将相关相互之间,就像在用户填写表单时,他还必须填写图像表单以便成功发布,我们会在视图中进行,但现在您的表单可能看起来像这样

You need to create a form for each model, but they will be related to each other, as in when the user is filling out the form post he has to complete the image form too for the post to successfully be posted, and we shall do that in the views, but for now your form can look something like this

class PostForm(forms.ModelForm):
    title = forms.CharField(max_length=128)
    body = forms.CharField(max_length=245, label="Item Description.")

    class Meta:
        model = Post
        fields = ('title', 'body', )


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

现在这是一切中最重要的部分,因为这是上传多个图像到一个魔法的地方。为了能够一次上传多张图像,我们需要多个图像字段?那就是你爱上了Django formets 的地方。我们将使用django formets来实现这一点,您可以在Django文档中阅读关于我们链接的文档的内容:)但是,您的视图应如下所示:

Now this is the most important part of everything, the views, because this is where uploading multiple images to a single magic happens. For us to be able to upload multiple images at once, we need multiple image fields right? That's where you fall in love with Django formsets. We will ned django formsets to make this happen, you can read about formsets in the Django documentation, which I have linked :) But here is how your view should look like:

@login_required
def post(request):

    ImageFormSet = modelformset_factory(Images,
                                        form=ImageForm, extra=3)

    if request.method == 'POST':

        postForm = PostForm(request.POST)
        formset = ImageFormSet(request.POST, request.FILES,
                               queryset=Images.objects.none())


        if postForm.is_valid() and formset.is_valid():



            post_form = postForm.save(commit=False)
            post_form.user = request.user
            post_form.save()

            for form in formset.cleaned_data:
                image = form['image']
                photo = Images(post=post_form, image=image)
                photo.save()
            messages.success(request,
                             "Yeeew,check it out on the home page!")
            return HttpResponseRedirect("/")
        else:
            print postForm.errors, formset.errors
    else:
        postForm = PostForm()
        formset = ImageFormSet(queryset=Images.objects.none())
    return render(request, 'index.html',
                  {'postForm': postForm, 'formset': formset},
                  context_instance=RequestContext(request))

在视图中,我们收到了两个表单,如果视图有效,则视图将检查两个表单。以这种方式,用户必须填写表单,并上传所有图片,这些图片在这种情况下为3 extra = 3 。只有这样才能成功创建该帖子。

In the view the we are getting both of our forms, and the view will check both forms if they are valid. In that way the user has to fill the form AND upload all the images which in this case are 3 extra=3. Only then will the post successfully get created.

您的模板应如下所示:

<form id="post_form" method="post" action=""
      enctype="multipart/form-data">

    {% csrf_token %}
    {% for hidden in postForm.hidden_fields %}
        {{ hidden }}
    {% endfor %}

    {% for field in postForm %}
        {{ field }} <br />
    {% endfor %}

    {{ formset.management_form }}
    {% for form in formset %}
        {{ form }}
    {% endfor %}


    <input type="submit" name="submit" value="Submit" />
</form>

您可以在我写的关于如何上传多个图片的博文中阅读更多信息 http://qasimalbaqali.com/django-uploading-multipleimages -for-a-single-post /

You can read more about it in a blog post that I wrote on how to upload multiple images http://qasimalbaqali.com/django-uploading-multiple-images-for-a-single-post/

这篇关于如何将多个图像上传到django中的博客文章的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆