Задать вопрос

Тел: +7 965 3737 888





Dynamic Django form

This is a little snippet that you can use to make your Django newforms dynamic at runtime. You can define an arbitrary number of fields of the form without loosing newforms capibilites. You can render the form dynamically be "misusing" the "help_text" attribute of the form fields (Every form field allows the definition of this attribute). This way you can search for changes in the help_text of every field and render the form accordingly.

The form itself is dynamically defined in the view.

The form state can be saved in a Django Session Variable (specifically for Linux users with a process-based Apache Server), so that you can rebuild and verify a submitted form.

Вопрос полезен? Да0/Нет0

Ответы (7):

Ответ полезен? Да0/Нет0

Could you please explain, how can change repesentation of form in html?

I can easily wright {{form}} or {{form.as_table}}, but I want locate them by myself.

Should I do smth like {{form.fields[k]}} ? (I can't make this work)

Ответ полезен? Да0/Нет0

Hi, imho it is good to add to it a function "is_valid". So form can be used as always.

if form.is_valid():
    # process it

Ответ полезен? Да0/Нет0

My modifications for accessing cleaned_data:

def validate(self, post):
    Validate the contents of the form
    self.cleaned_data = {}
    for name,field in self.fields.items():
            self.cleaned_data[name] = field.clean(post[name])
        except ValidationError, e:
            self.errors[name] = e.messages

Ответ полезен? Да0/Нет0

I couldn't find how I can access the cleaned_data and in fact why you are creating a different method validate instead of using self.full_clean() or something similar. I just changed the validate to:

def validate(self): self.full_clean()

for readability sake and now I can access:


Ответ полезен? Да0/Нет0

Nice. This came in handy, but it doesn't play well with multivalue fields.

I had to modify setData and validate to deal with this situation:

def setData(self, kwds):
    """Set the data to include in the form"""
    for name,field in self.fields.items():
        self.data[name] = field.widget.value_from_datadict(
                            kwds, self.files, self.add_prefix(name))
    self.is_bound = True

def validate(self, post):
    """Validate the contents of the form"""
    for name,field in self.fields.items():
        value = field.widget.value_from_datadict(
                            post, self.files, self.add_prefix(name))
        except forms.ValidationError, e:
            self.errors[name] = e.messages

Ответ полезен? Да0/Нет0

How can i use this? thanks

Ответ полезен? Да0/Нет0

This is great, but to make it work you need to modify setData to add the line:

self.is_bound = True

Otherwise when you display the form it ignores the data