Django-在提交时保存数据,但不重新加载视图 [英] Django - save data on submit but not reload view

查看:24
本文介绍了Django-在提交时保存数据,但不重新加载视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个视图,该视图显示可以使用提交按钮保存的表单.我不希望在提交表单时重新加载视图.但是,如果函数不返回响应,则会出错.

I have a view that display a form that can be saved with a submit button. I dont want the view to be reloaded when the form is submit. However, I have an error if the function do not return a response.

view.py

from django.shortcuts import render_to_response
from ezmapping.models import *
from django.forms.models import modelformset_factory

def setAppOptions(request, map_name):
    if request.user.is_authenticated():
        app_selected = EzApp.objects.get(app_name=app_name, created_by=request.user)
        formset = ezAppOptionFormSet(user=request.user, instance=app_selected)
        if request.method == 'POST':
            formset = ezAppOptionFormSet(request.POST, instance=app_selected, user=request.user)
            if formset.is_valid():
                formset.save()

        return render_to_response("manage_app_options.html", {'formset': formset}, context_instance=RequestContext(request)) 
    else:
        error_msg = u"You are not logged in"
        return HttpResponseServerError(error_msg)

推荐答案

除非重新提交模板,否则您将无法执行POST,除非您通过ajax发布表单.如果您通过ajax提交表单并返回JSON,XML等响应,则可以使用表单错误或其他信息来更新模板.

You won't be able to do the POST without re-rendering the template, unless you're posting the form via ajax. If you submit the form via ajax and get a response back that is JSON, XML, etc, you can then update the template with the form errors or other information.

但是,考虑到您的视图中概述的用例,我建议使用

However, given the use case outlined in your view, I would suggest limiting access to the view altogether using the @login_required decorator. If you do that, your view logic can be greatly simplified.

这篇关于Django-在提交时保存数据,但不重新加载视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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