V
V
Victor Victor2013-12-16 14:24:59
Django
Victor Victor, 2013-12-16 14:24:59

How to implement validation and processing of submitted data in Django 1.5.4?

There is a form:

<form method="post" action="">
    <fieldset id="books">
        <legend>Книги прочитанные в этом году:</legend>
        <p  class="cloneMe">
            <label>Название: <input type="text" name="book_title[]" /></label>
            <label>Автор: <input type="text" name="book_author[]" /></label>
        </p>
        <button type="button" id="js-clone">Добавить</button>
    </fieldset>
    <input type="submit" value="отправить" />
</form>

And javascript:
$('#js-clone').on('click', function () {
    var $clones = $('.cloneMe:last').clone();
    $clones.find('input').val('');
    $(this).before($clones);
});

Example at jsfiddle.net .
The question is, how in Django (Django==1.5.4) to implement validation and processing of submitted data?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pavel Zagrebelin, 2013-12-16
@toptalo

formset?

A
alz, 2013-12-16
@alz

Custom widget and field needed

from django import forms
from django.utils.datastructures import MultiValueDict, MergeDict

class Widget(forms.widgets.Widget):
    def value_from_datadict(self, data, files, name):
        if isinstance(data, (MultiValueDict, MergeDict)):
            return data.getlist(name)
        return data.get(name, None)

    def render(self, name, value, attrs=None):
        pass # TODO: render widget

class Field(forms.Field):
    def to_python(self, value):
        if not value: return []
        return filter(None, value)

This is the most primitive implementation. No additional checks and no widget rendering

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question