0

I have a django app where user can submit a form .I have put this form inside a div (say of id='mydiv_id') which is initially invisible(by css display:none).When a user want to enter the input ,he clicks a show button on the page ,and a javascript makes the div visible by making display:block.

The fields in the form have {{myform.myfield.errors}} so that a ul class="errorlist" will be created if validation fails.

I want to keep the form visible by running another javascript if the form validation fails.The body of javascript will be just $('#mydiv_id').show();

But how should I make this run? How do you tell the javascript that django form validation failed without doing the validation inside the javascript?

I think I need to put the following in javascript body..Other than that I can't figure out how to tell it that form submission failed.

$(document).ready(function(){

..
});

3 Answers 3

1

if i understand you well

$(document).ready(function(){
    show = {% if form.errors %} true {% else %} false {% endif %}
    if (show) {
       $('#mydiv_id').show();
    }
    else {
    ....
    }

)};
Sign up to request clarification or add additional context in comments.

Comments

1
def method(request):
    if something_wrong:
        data['error'] = True
    return render_to_response('template.html', data)

and in the template.html you can add the javascript block:

{% if error %}
<script type='text/javascript'>
    //the javascript used to show the message
    $(function(){
        $('#mydiv_id').show();
    });
</script>
{%endif%}

Comments

0

Using javascript to do form validation is a smart thing to do, why make a call to the server if the form is not valid? You are just making extra overhead to your server by making it do form validation. If you do not need to call the server to do form validation there is no reason you should, use javascript to do that.

2 Comments

suppose a user turns off javascript and submit,then I will be in trouble with server side validation turned off
In that case you wont be running any javascript. You would submit via a regular post if django form validate does not pass you would pass back that invalid form for display with errors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.