开发者

Grabbing data from middleware form using jQuery in Django

I have a middleware like this:

class PostModelFormMiddleware(object):

def process_request(self, request):

    form = PostModelForm()
    request.post_form = form

This form has a captcha field. What I want to happen in my template is everytime a person hits Submit the captch question refreshes by Javascript to a new one. How do I grab that request.post_form and its data in jQuery?

Thank you!

EDIT: More code.

The HTML:

   <form id="add_post">
...
        <input type="hidden" name="math_captcha_question" value="fbc9fcdffbf2b2723ab36e9f341372214daf1be936202d2035">
    6 - 5 = 
...
    </form>

I would like to change the value of "math_captch_question" as well as the displayed text. Both of these are initially displayed using the template tag {{request.post_form.math_captcha_question}}

The开发者_开发知识库 jQuery:

 $("form#add_post").submit(function() {
 //Validations and stuff
            var data = {category:category, body:body, nickname:nickname, math_captcha_question:math_captcha_question, math_captcha_field:math_captcha_field};
            var args = {type:"POST", url:"add_post/", data:data, complete:function(res, status) {
                //Process response
                //This is where I would like to set new values for math_captcha_question

            } };

            $.ajax(args);
        }


        return false;

    })

/add_post/ view:

def add_post(request):
    if request.method == 'POST':

        if form.is_valid():
           #do stuff
           return HttpResponse("success")

        else:
            return HttpResponseServerError("fail")


You have to output the form in your template first, give it an id or other identifier and then you can access it via jQuery.

<form id="myform" ...>
    {{request.post_form}}
</form>

Edit: I am assuming you have 'django.core.context_processors.request' in your TEMPLATE_CONTEXT_PROCESSORS setting.

Update (according to comments below):

Your add_post view need to return something in the response jQuery.ajax can deal with. If it is just returning "success" there will be only plain text in the response. To make it easy you should return the new math_captcha_question value:

def add_post(request):
    if request.method == 'POST':
       #fill some data in the form
       form = PostModelForm(request.POST)
       if request.post_form.is_valid()
            math_captcha_question = form.cleaned_data["math_captcha_question"]
            return HttpResponse(math_captcha_question)
       else:
            return HttpResponse("error")

In the callback in jquery you can then deal with the values you get and give a user friendly response accordingly. In you on complete callback:

function(res, status) {
    if (res!="error") {
        $("form#add_post #id_math_captcha_question").attr("value", res);
    } else {
        //show some error to your user
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜