[Answer]-Django: updating src on iframe without refreshing

1👍

Well, you have to show us more details, view, models some html and javascript that you already have. However, I’ll make a simple way to do it.

#models.py

Class Page(models.Model):
    url = models.URLField()

#views.py

def random_page_view(request):
    response_data = {}
    page = Page.objects.order_by('?')[0]
    response_data['page_url'] = page.url
    return HttpResponse(json.dumps(response_data), content_type="application/json")

#random_page.html

<!-- I guess you have something like -->
<iframe id='random-page' src='some url'></iframe>
<button id='new-page-button'>Click me!</button>

<script>
  $(function(){
    $('#new-page-button').on('click', function(event){
        $.get( "{% url 'get_random_url' %}", function( data ) {
           $( "#random-page" ).attr('src', data.page_url);
        });
    });
  })
</script>

NOTE: Maybe you dont have to use order_by(‘?’), it’s slow. (see here)

NOTE 2: If you dont have any Page, it’s gonna fail 🙂

Leave a comment