Home > Enterprise >  Populate Python object with Django Form
Populate Python object with Django Form

Time:11-20

I am trying to use a Django form to populate a Python object (not a Django model). I have the feeling I can only either:

  • build a simple form and populate manually
  • use a Django model as proxy

The extra difficulty is the form send a GET request

The class

class Search:
      
    def __init__(self):
        self.min_area = 0
        self.max_area = 999

The form

from django import forms


class MainSearchForm(forms.Form):

    min_area = forms.IntegerField(label="Minimum", required=False)
    max_area = forms.IntegerField(label="Maximum", required=False)

The view

from django.http import HttpResponse
from django.template import loader
from front.forms.search.main import MainSearchForm
from front.gears.search import Search


def main(request):

    search = Search()
    form = MainSearchForm(request.GET, {})

    # manual populating i want to avoid
    if form.has_changed() and form.is_valid():
        search.min_area = form.cleaned_data['min_area']
        search.max_area = form.cleaned_data['max_area']

    tpl = loader.get_template('front/search/main.html')
    ctx = {
        'form': form,
        'search': search
    }

    return HttpResponse(tpl.render(ctx, request))

For now, I am populating manually in the view but I am quite sure there is a better way to do it. Am I missing a part of the documentation ?

CodePudding user response:

You can use setattr:

for key in form.cleaned_data:
    setattr(search, key, form.cleaned_data[key])

  • Related