Back
Mar 6, 2010

Ajax form validation

Vladimir Sidorenko
Vladimir Sidorenko

There was a task to submit form with ajax, with server side validation of course. Obvious solution is to do validation and return json with erros.

I didn't like idea of writing separate view for validation and then inserting errors in form html on client side. Especially since I already had a generic template for django form with errors display.

Task

User will see process like this:

  • User clicks 'edit' near article block
  • article is replaced with form
  • in case there are validation errors - they are shown above the form fields
  • in case there are no errors - form is replaced by article html

Solution

Server will return piece of html that will replace part of page with article or form (with errors if needed). Actually this sentence is the most important part of this blog post. Implementation is very simple and straightforward.

Well actually the fact that you can return parts of html from server is also not new idea at all. It's just only now I finally understood that using this technique you can create more complicated things than modal window or tabs

Implementation

views.py

def edit_new(request, new_id):
        new = get_object_or_404()
        if request.method == 'POST':
            form = NewsForm(request.POST, instance=new)
            if form.is_valid():
                new = form.save()
                return render_to_response('include/new.html', dict(new=new))
        else:
            form = NewsForm(instance=new)
        return render_to_response('include/form.html', dict(form=form, new=new))

form.html

This html will replace article block on 'edit' button click. Javascript should be moved to separate file of course.

<script type="text/javascript">
        function submitAndLoad(input) {
            $.ajax({
                url: "{% url edit_new new.id %}",
                data: $(input).parent().serialize(), // форма
                type: "post",
                dataType: "html",
                success: function(data) {
                    $(input).parent().parent().html(data); // article block
                }
            });
            return false;
        };
    </script>
    <form>
        {{ form }}
        <input type="submit" value="Save" onclick="return submitAndLoad(this);"/>
    </form>

news_list.html

<script type="text/javascript">
        function editNew(id) {
            $("#new-" + id).load("{% url edit_new new.id %}");
            return false;
        }
    </script>

    <!-- ... -->

    <div id="new-{{ new.id }}">
        {% include "news/new.html" %}
    </div>
    <a onclick="return editNew({{ new.id }});" href="#">Edit</a>

Code can be cleaned up of course, I just wanted to show the idea.

Update

I'm translating this article almost five years after it was originally written and of course now it seems very childish :) Now we have angular and ajax forms are implemented a little differently. Still this old solution is not all that bad. I'd still replace one thing here - it's better to return json with html from server instead of just html.

More thoughts

Sep 1, 2021TechnologyBusiness
Top 10 Web Development Frameworks in 2021 - 2022

We have reviewed the top web frameworks for server and client-side development and compared their pros and cons. Find out which one can be a great fit for your next project.

Marina Sharapova
Marina Sharapova
May 9, 2018Technology
How to Generate PDF Files in Python with Xhtml2pdf, WeasyPrint or Unoconv

Programmatic generation of PDF files is a frequent task when developing applications that can export reports, bills, or questionnaires. In this article, we will consider three common tools for creating PDFs, including their installation and converting principles.

Vladimir Sidorenko
Vladimir Sidorenko
Feb 18, 2010Technology
Business logic in models

In my recent project there was a lot of data business logic, so I had to organize this code somehow. In this article I'll describe a few hints on how to it.

Vladimir Sidorenko
Vladimir Sidorenko
Feb 12, 2020Technology
5 Best Payment Gateways For 2020

We reviewed the best payment gateways in 2020. Here’s our comparison of their features, advantages, and disadvantages.

Vladimir Sidorenko
Vladimir Sidorenko
Oct 11, 2010Technology
Char search in Emacs as in Vim

In VIM there is a command for char search: f. After first use it can be repeated with ;. I like to navigate in line with it. You see that you need to go to bracket in a middle of a line - you press f( and one-two ; and you are there. There's no such command in Emacs, so I had to write my own. I've managed even to implement repetition with ;.

Vladimir Sidorenko
Vladimir Sidorenko
Mar 6, 2010ManagementTechnology
Supplementing settings in settings_local

For local project settings, I use old trick with settings_local file:try:from settings_local import \*except ImportError:passSo in settings_local.py we can override variables from settings.py. I didn't know how to supplement them. For example how to add line to INSTALLED_APPS without copying whole list.Yesterday I finally understood that I can import settings from settings_local:# settings_local.pyfrom settings import \*INSTALLED_APPS += (# ...)

Vladimir Sidorenko
Vladimir Sidorenko