Usually, I always use JQuery to solve this kind of problems. Here is the example, which is a simple example, you have to change the necessary part.
Description:
Select a user in the page, and the article will change to the articles belong to the selected user.
The urls.py
from TestDjango.testdb import testdb, getArticlesByUser
urlpatterns = [
......
url(r'^testdb/$', testdb, name='testdb'),
url(r'^getarticles/$', getArticlesByUser, name='get_art'),
......
]
testdb.py
from django.shortcuts import render
from Articles.models import Articles
from Users.models import Users
def testdb(request):
context = {
'users': Users.objects.all(),
}
return render(request, "Users/list.html", context)
def getArticlesByUser(request):
# get parameters from page - Users/list.html
user_id = request.GET.get('user_id', None)
# get data from database by using "user_id"
list_articles = Articles.objects.filter(user_id=user_id)
str_alltitle = ""
for item in list_articles:
str_alltitle += '<option value="' + str(item.id) + '"> ' + item.title + ' </option> '
# return a json response to the html
from django.http import JsonResponse
return JsonResponse({'articles': str_alltitle})
list.html
{% extends "base.html" %}
{% block title %}
List Articles By User ID - User
{% endblock %}
{% block mainbody %}
<p>
<span>User:</span>
<select id="user" name="user_id">
<option value="">---Empty---</option>
{% for user in users %}
<option value="{{ user.id }}" > {{ user.email }} </option>
{% endfor %}
</select>
</p>
<p>
<span>Articles:</span>
<select id="article" name="article_id"></select>
</p>
{% endblock %}
{% block scriptsection %}
<script type="text/javascript">
$('#user').bind('change', function () {
$.ajax({
url: '/getarticles/?user_id='+ this.value,
type: 'GET',
success: function (json) {
$('#article').html(json['articles'])
}
});
});
</script>
{% endblock %}
This is working in my computer, I use python 3.4 and Django 1.10.4!