9m8fua
Last Updated: February 25, 2016
·
3.008K
· voiddragon

Set initial data for large forms in django

So I had a search function for a site I was building, first it was 4 fields, then 6, then 8. and the get_initial on my view was starting to look ridiculous.

def get_initial(self):
    if self.request.GET:
        initial = {
                    'item1', self.request.GET.get('item1', None),
                    'item2', self.request.GET.get('item2', None),
                    'item3', self.request.GET.get('item3', None),
                    'item4', self.request.GET.get('item4', None),
                    'item5', self.request.GET.get('item5', None),
                    'item6', self.request.GET.get('item6', None),
                    'item7', self.request.GET.get('item7', None)}
        return initial
    else:
        return super(ProjectListView, self).get_initial()

And sooner or later it's just going to get longer and longer

So I asked the other dev was there any less retarded way of doing this.

And the code became

def get_initial(self):
    if self.request.GET:
        initial = self.request.GET.dict()
        return initial
    else:
        return super(ProjectListView, self).get_initial()

Much better.

1 Response
Add your response

22658

"initial = self.request.GET" works too. As mentioned in the docs, it returns "A dictionary-like object containing all given HTTP GET parameters"

https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.GET

over 1 year ago ·