Django - 从模板内部调用带有表单的视图

Django - Call a view with forms from inside a template

我想将几个帐户管理页面放在一个页面上。单击左侧的 link 将通过 ajax 将相应的视图(shipping/account 信息、购物车等)加载到右侧的 div 中。例如:单击 'View Cart' 将调用 render_cart 视图并将生成的模板插入同一页面上的另一个 div。

在我开始介绍表单之前,这一切都很好。正确填写表格后,它似乎可以正常工作。不完整的表格将 return 仅包含内部模板(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})

我建议您发送带有 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)
    });
});

响应将包含带有错误消息或成功消息的更新表单。

一般来说,我建议您针对不同的操作使用单独的视图。