django jquery-form .load() if form errors

随声附和 提交于 2020-03-06 00:02:25

问题


I am loading a form to a popup div using the jquery.load() function and so far it is working nicely. What i would like to add is when the form is submitted with errors it will load the error mark up form back into the popup div instead of redirecting to the actual form page, which it is currently doing.

Someone recommended that I use jquery-form which i think would work perfectly. I just don't know how to implement it.

here is the .load() function:

$(document).ready(function(){
        $(".create").on("click", function(){
            $("#popupContact").load("/cookbook/createrecipe #createform");
        });
});

here is the page that loads the form:

<div id="popupContact" class="popup">
        <a id="popupContactClose" style="cursor:pointer;float:right;">x</a>
        <p id="contactArea">
        </p>
</div>
<div id="backgroundPopup">
</div>  
<div id="col2-footer">
{% paginate %}
</div>

here is my form template:

<div id="createform">
<h1>Create New Recipe</h1>
    <form id="createrecipe" action="{% url createrecipe %}" method="POST">
        <table>
            {% csrf_token %}
            {{ form.as_table }}
        </table>
        <p><input type="submit" value="Submit"></p>
    </form>
</div>

here is my attempt to use the jquery-form:

<script> 
    // wait for the DOM to be loaded 
    $(document).ready(function() { 
        var options ={
            target: '.popup',
    };
    $('#createrecipe').submit(function() {
        $(this).ajaxSubmit(options); 
        return false;
    }); 
});
</script> 

createrecipe view:

def createrecipe(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/index/')
    else:
        if request.method == 'POST':
            print 1
            form = RecipeForm(request.POST)
            if form.is_valid():
                print 2
                recipe = form.save(commit=False)
                recipe.original_cookbook = request.user.cookbooks.all()[0]
                recipe.pub_date = datetime.datetime.now()
                recipe.save()
                user = request.user
                cookbooks = user.cookbooks
                cookbook = cookbooks.all()[0]
                cookbook.recipes.add(recipe)
                return HttpResponseRedirect('/account')
        else:
            form = RecipeForm()

        return render_to_response('cookbook/createrecipe.html',
                                    {'form':form},
                              context_instance=RequestContext(request))

thank you snackerfish


回答1:


Because you use jquery anyway you should submit your form via ajax otherwise you will be redirected:

 $('#createform form').submit(function(e) {
 e.preventDefault();
 $.post("/your views url/", { 
            data: $('#createform form').serialize(),
            },function(data){ //this is the successfunction 
                              //data is what your view returns}
 });

Your view should return the errors as json so that you can process them inside your javascript:

from django.utils import simplejson

def ajax_recipe(request):
    if request.method == 'POST':
        form = YourForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponse("ok")
        else:
            errors = form.errors
            return HttpResponse(simplejson.dumps(errors))
    else:
        data = "error"
        return HttpResponse(data)

With that markup you can place your form errors where ever you want, using the jquery post success function.

if(data == "ok"){do something}
// else error handling
var errors = jQuery.parseJSON(data)
if(errors.somefield){//place errors.somefield anywhere}

Note the code is not tested. But thats the way I would go.

Edit

Note to make this work you have to set a custom X-CSRFToken header to the value of the CSRF token on each XMLHttpRequest. in other words copy and paste the script from the django docs inside your template: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

Thats how you could raise the errors insid your Form.py

def clean_somefield(self):
        somefield = self.cleaned_data.get('some field')
        if not somefield:
            raise forms.ValidationError(u'This field is required.')



回答2:


i had an error in the syntax of my javascript all is ok



来源:https://stackoverflow.com/questions/10286242/django-jquery-form-load-if-form-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!