Grabbing data from middleware form using jQuery in Django -


i have middleware this:

class postmodelformmiddleware(object):  def process_request(self, request):      form = postmodelform()     request.post_form = form 

this form has captcha field. want happen in template everytime person hits submit captch question refreshes javascript new one. how grab request.post_form , 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 change value of "math_captch_question" displayed text. both of these displayed using template tag {{request.post_form.math_captcha_question}}

the jquery:

 $("form#add_post").submit(function() {  //validations , 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 set new values 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 output form in template first, give id or other identifier , can access via jquery.

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

edit: assuming have 'django.core.context_processors.request' in template_context_processors setting.

update (according comments below):

your add_post view need return in response jquery.ajax can deal with. if returning "success" there plain text in response. make easy should return new math_captcha_question value:

def add_post(request):     if request.method == 'post':        #fill data in 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 callback in jquery can deal values , give user friendly response accordingly. in on complete callback:

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

Comments

Popular posts from this blog

objective c - Change font of selected text in UITextView -

php - Accessing POST data in Facebook cavas app -

c# - Getting control value when switching a view as part of a multiview -