English 中文(简体)
django jquery-form .load()
原标题:django jquery-form .load() if form errors

我在装上一种表格,使用舱载()功能,迄今为止,它正在做出色的工作。 我要补充的是,如果提交表格时出现错误,就会把错误标记重新装入人口编组,而不是改用目前实际的纸页。

有些人建议我使用jquery-form。 我认为,这将完全奏效。 我不知道如何执行。

此处为有效载荷功能:

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

The page thatloads 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>

我的形式模板如下:

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

形成反感:

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

最佳回答

i) 我的javascript的辛醇全都是ok。

问题回答

既然你使用 j,你就应该通过麻省提交你表格,否则你将改头:

 $( #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)

有了这一标志,你就能够把你想要的那类错误放在你身上,利用破碎后的成功功能。

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

请注意,要完成这项工作,你必须确定一个习惯X-CSRF Token Header to the Value of the CSRF token on each XMLHttpRequest。 http://docs.djangoproject.com

您可以如何提出错误,以证明您的表态。

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




相关问题
How to get two random records with Django

How do I get two distinct random records using Django? I ve seen questions about how to get one but I need to get two random records and they must differ.

Moving (very old) Zope/Plone Site to Django

I am ask to move data from a (now offline) site driven by Plone to a new Django site. These are the version informations I have: Zope Version (unreleased version, python 2.1.3 ) Python Version 2.1....

Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

Flexible pagination in Django

I d like to implement pagination such that I can allow the user to choose the number of records per page such as 10, 25, 50 etc. How should I go about this? Is there an app I can add onto my project ...

is it convenient to urlencode all next parameters? - django

While writing code, it is pretty common to request a page with an appended "next" query string argument. For instance, in the following template code next points back to the page the user is on: &...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

热门标签