1

I use modelformset_factory to upload image, but I want to separate the already saved image (A in the below link) and upload image (B in the below link) on two different html template.

How do I resolve this problem?

enter image description here

Here is my code below:

views.py

def post_image(request):

    PictureFormSet = modelformset_factory(Picture, form=PictureForm, extra=3)

        if request.method == 'POST':
    
            formset = PictureFormSet(request.POST, request.FILES)
    
            if formset.is_valid():
        
                formset.save()
        
                return HttpResponse("Upload done!!")
    
            else:
        
                return HttpResponse("Upload Failed!!")

        else:
    
            formset = PictureFormSet()
    
            return render(request, "Image.html", {"formset": formset})

models.py

    class Picture(models.Model):
        article = models.ForeignKey("Article", related_name="article_photo", on_delete=models.CASCADE)
        photo = models.ImageField(upload_to="photo", height_field=None, width_field=None, max_length=100)
        first_photo = models.BooleanField(default=False)

urls.py

    path('post/image/', post_image),

html

    <html lang="zh-Hant-TW">
    <head>
    <meta charset="UTF-8">
    <title>post_image</title>
    </head>
    <form action="" method="POST" enctype="multipart/form-data">{% csrf_token %}
        {{ formset.management_form }}
        <table>
            {% for form in formset %}
                {{ form }}
            {% endfor %}
        </table>
        <input type="submit" value="Sumbit">
    </form>
furas
  • 134,197
  • 12
  • 106
  • 148
ethon
  • 21
  • 2
  • you can render two templates to strings, join them and send to browser as one string. – furas Jan 03 '21 at 11:07
  • but I don't know how to split two parts in views code. – ethon Jan 04 '21 at 04:51
  • I don't know if I understand but you can use [render_to_string()](https://docs.djangoproject.com/en/3.1/topics/templates/#django.template.loader.render_to_string) to render two templates to strings (every template only with `form`, without ``, ``) and use both in finall template which adds ``, `` - `return render(request, 'base.html', content=template1_string+template2_string)` – furas Jan 04 '21 at 14:24
  • I only use "save()" function that cause two parts in my view code. I do not know how to present B part in view code. – ethon Jan 08 '21 at 08:54
  • I guess that present two parts function comes from "save()" base code. But i cannot find source code. – ethon Jan 08 '21 at 09:10

0 Answers0