Django - 使用模板内部的表单调用视图

时间:2015-08-29 20:10:27

标签: ajax django django-forms django-templates django-views

我想在一个页面上放置几个帐户管理页面。单击左侧的链接将通过ajax将相应的视图(送货/帐户信息,购物车等)加载到右侧的div中。例如:单击“查看购物车”将调用render_cart视图并将生成的模板插入到同一页面上的另一个div中。

这一切正常,直到我开始介绍表格。当表单填写正确时,它似乎正常工作。不完整的表单将仅返回内部模板(render_cart,但不包含包含的帐户管理模板)。我可以改变它来渲染外部视图,但后来我丢失了表单错误和成功消息。

代码如下。

使用Javascript:

function render_account_info() {
    var account_info = $.get({% url 'account-info' %}, function(response) {
        $('#account-edit').html(response);
    });
}

HTML:

<!-- account.html - this is the main account management template -->
{% block content %}
<div style="float: left;">
    Account Info<br />
    Shipping Info</br />
    Cart<br />
</div>
<div style="float: right; width: 50%;" id="account-edit">
</div>
{% endblock %}


<!-- account_info.html - this is the account info template (change email and password) -->
Hello, {{ request.user }}!<br />
<form action="{% url 'account-info' %}" method='POST'>
    {% csrf_token %}
    {{ passwordForm.as_p }}
    <input type="submit" value="Submit">
</form>

Django观点:

#this loads the main account management page
@login_required(login_url = reverse_lazy('login'))
def account(request):
    return render(request, 'website/account.html')


#this view is meant to change passwords and email addresses
#the commented out lines below are examples of what I have tried to get forms working right
@login_required(login_url = reverse_lazy('login'))
def render_account(request):
    c = {}
    c.update(csrf(request))
    passwordForm = PasswordChangeForm(user = request.user)
    if (request.method == 'POST'):
        passwordForm = PasswordChangeForm(user = request.user, data = request.POST)
        if (passwordForm.is_valid()):
            passwordForm.save()
            update_session_auth_hash(request, passwordForm.user)
        #return render(request, 'website/account_info.html', {'passwordForm': passwordForm})
        return render(request, 'website/account.html')
        #else:
            #return render(request, 'website/account.html')
    return render(request, 'website/account_info.html', {'passwordForm': passwordForm})

1 个答案:

答案 0 :(得分:2)

我建议您使用Ajax调用发送表单,并将响应html动态插入主div。

$('form').submit(function(e){
    e.preventDefault();
    var data = $('form').serialize();
    $.post('{% url 'account-info' %}', data).success(function(data){
        $('#account-edit').html(data)
    });
});

响应将包含更新的表单,其中包含错误消息或成功消息。

通常我建议您根据不同的操作使用单独的视图。