how to upload multiple images to a blog post in django

前端 未结 4 1723
灰色年华
灰色年华 2020-11-28 02:35

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

4条回答
  •  囚心锁ツ
    2020-11-28 03:08

    Step by step solution => Even, I was stuck too. So this is how I successfully do.

    Finally, implementing below code, I achieved this

    • 1 Note model with many Images
    • Multiple Uploads(at the same time, with same Choose File button, & all save together as like in Gmail file upload)

    Here are my Note and Image Model- (or see full code)

    class Note(models.Model):
        user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
        title = models.CharField(max_length=30)
        text = models.TextField(null=True,blank=True)
        created_date = models.DateTimeField(auto_now_add=True)
        last_modified = models.DateTimeField(auto_now=True)
    
    class Images(models.Model):
        note = models.ForeignKey(Note,on_delete=models.CASCADE)
        image = models.ImageField(upload_to=user_directory_path,null=True,blank=True)
    

    Here is my form (Link of doc. on multiple upload)- (or see full code)

    class NoteForm(forms.ModelForm):
        class Meta:
            model = Note
            fields = ['title','text'] #make sure to mention field here, if nothing is mentioned then all will be required.
    
    class NoteFullForm(NoteForm): #extending form
        images = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
    
        class Meta(NoteForm.Meta):
            fields = NoteForm.Meta.fields + ['images',]
    

    Here is my View file- (or see full code)

    def addNoteView(request):
    if request.method == "POST":
        #images will be in request.FILES
        form = NoteFullForm(request.POST or None, request.FILES or None)
        files = request.FILES.getlist('images')
        if form.is_valid():
            user = request.user
            title = form.cleaned_data['title']
            text = form.cleaned_data['text']
            note_obj = Note.objects.create(user=user,title=title,text=text) #create will create as well as save too in db.
            for f in files:
                Images.objects.create(note=note_obj,image=f)
        else:
            print("Form invalid")
    

    And, finally my Html file (be sure to bind files as said in docs)- (or see full code)

    {% csrf_token %}

提交回复
热议问题