Reputation: 393
I'm trying to use AJAX to update a Django context dictionary so that it can display different assignments on a web page when a certain button is clicked. My view creates a different context dictionary based on either GET or POST methods used to request the page. The former is the default and the later occurs when the user clicks the button. Everything works, the AJAX sends the correct data and the view is able to find the correct corresponding assignments. My issue, however, is that the page content (the django template code) never changes updates with the response. What am I doing wrong?
@login_required
def assignments(request):
terms = Course.objects.filter(students = request.user).values('term__season', 'term__year').distinct()
courses = Course.objects.filter(students = request.user)
assignments = Assignment.objects.filter(course__in=courses)
if request.method == 'POST':
# retrive ajax data
data = request.POST
course_subject = data['course_subject']
course_number = data['course_number']
course_section = data['course_section']
term_season = data['term_season']
term_year = data['term_year']
# get the associated course for the click
course = Course.objects.filter(subject = course_subject,
number = course_number,
section = course_section,
term__year = term_year,
term__season = term_season)
# get the assignments associated with that course
assignments = Assignment.objects.filter(course = course)
context_dict = {
'assignments': assignments,
'courses': courses,
'terms': terms,
}
return render(request, 'mainapp/assignments.html', context_dict)
Upvotes: 1
Views: 2232
Reputation: 1444
The page won't magically "redraw" itself. You should reload it (do real form submit) or modify page content using Javascript. I'd recommend to split your functionality into 2 views. The first one would render initial state of the page and the second one would handle Ajax requests. Ajax handling view could either render HTML (you would directly insert on the page) or JSON (then you would need to implement actual HTML rendering on the client side).
Upvotes: 3