Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to include a view within another template

I am using a 3rd party Django package to manage my avatar upload and display in my website. The package requires the upload view to display in a new window and is configured as normal in Django in urls.py like so:

 url(r'^avatar/', include('avatar.urls')),

So that when I go to mysite.com/avatar/add.html I see the add view for uploading an avatar.

What I want to do is to create a modal window in my main view which loads the avatar upload view (add.html) into the same view. I have achieved this by doing:

{% include 'avatar/add.html' %}

But what I realise is it displays everything but the upload form, because django does not get a chance to run the 3rd avatar view code associated with this template to inject the context before rendering out in the same way it would if I access it as a URL.

My question is: Is it possible to get inline a 3rd party view Django so that it processes it and injects into my own view/template at render time, still respecting the GET/POST logic in the 3rd party view?

I have full access to the 3rd party view code (which is a view function, I'm using class based view), but heaven forbid me copying and pasting their code into my own which defeats purpose.

Thanks in advance

like image 930
Francis N Avatar asked Dec 14 '25 04:12

Francis N


1 Answers

Ok I just solved this quite nicely like so:

In my views.py class I imported the 3rd party view I want to inline in my view

views.py

from avatar import views as avatar_view

then in the get() method of my class based view

def get(self, request, *args, **kwargs):
    user =  CreativeUserProfile.objects.get(id = request.user.id)

    /*
       Get Django to parse the 3rd party view and capture it's HttpResponse.
       add() is a view function which specifies it's own template:
       avatars/add.html and injects it's form into it
     */
    avatar_html = avatar_view.add(request).getvalue()

    /* Push the resulting html into my template's own context */
    return render(request, self.template_name, {'user':user,
                                                'avatar_html': avatar_html})

Now in my template file I simply do this

profile.html

 <!--  Avatar popup window -->
 <div class="modal">
    <div class="avatar-modal">
        <span class="avatar-close-btn">&times;</span>
        {{ avatar_html|safe }}
    </div>
 </div>

Now I get the html of the 3rd party avatar rendering with the form which works very well!

If anyone can see any potential pitfalls with this approach I would humbly appreciate your expert critique.

Many thanks and hope this helps others

like image 67
Francis N Avatar answered Dec 16 '25 21:12

Francis N



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!