是否可以在不重新加载页面的情况下更新Django上下文词典? [英] Is it possible to update a django context dictionary without reloading the page?

查看:38
本文介绍了是否可以在不重新加载页面的情况下更新Django上下文词典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用AJAX更新Django上下文字典,以便单击某个按钮时它可以在网页上显示不同的任务.我的视图基于用于请求页面的GET或POST方法创建了一个不同的上下文字典.前者是默认设置,而后者在用户单击按钮时发生.一切正常,AJAX发送正确的数据,并且视图能够找到正确的相应分配.但是,我的问题是页面内容(django模板代码)从不更改响应的更新.我在做什么错了?

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)

推荐答案

页面不会神奇地重绘"自身.您应该重新加载它(执行真实表单提交)或使用Javascript修改页面内容.我建议将您的功能分为2个视图.第一个将呈现页面的初始状态,第二个将处理Ajax请求.Ajax处理视图可以呈现HTML(您可以直接在页面上插入)或JSON(然后您需要在客户端上实现实际的HTML呈现).

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).

这篇关于是否可以在不重新加载页面的情况下更新Django上下文词典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆