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

Тел: +7 965 3737 888

443

Просмотров

3

Ответов

DRYer instantiation of Forms

<p>Using this small helper, you can instanciate your forms in an even DRYer way:
</p>
form = MyForm(**form_kwargs(request))
if form.is_valid():
    #...

Вопрос полезен? Да0/Нет0
file_2493.py(175.0б)
None

Ответы (3):

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

PS: if you'd rather not bother with a helper like this, the method of instanciating a form only once for both cases is still useful.

The most simple case is (where files aren't involved and you always expect at least one thing in your POST):

form = MyForm(data=request.POST or None)
if form.is_valid():
    form.save()
    # Redirect

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

Normally, you'd write:

if request.method == 'POST':
    form = MyForm(data=request.POST, files=request.FILES)
    if form.is_valid():
         form.save()
         # Redirect
else:
    form = MyForm()

Now you write:

form = MyForm(**form_kwargs(request))
if form.is_valid():
     form.save()
     # Redirect

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

Maybe its just me, but I don't see how this is "DRY"er. Not even sure what the point of it is.