Prabhakaran
Prabhakaran

Reputation: 4013

django url parameters as form default value

I have a search form

class PostSearchForm(forms.Form):
    keyword = forms.CharField(label=_('Search'))
    def __init__(self,*args,**kwargs):
        self.request = kwargs.pop('request', None)
        super(PostSearchForm,self).__init__(*args,**kwargs)
        raise Exception(self.request)    # This returns none
        categories = Category.objects.filter(status=True)
        self.fields['categories'] = forms.ModelChoiceField(queryset=categories, widget=forms.SelectMultiple(attrs={'class': 'some-class'}))

Whenever search is made I have a build a form with default value as what they have searched, so what I tried is get the url parameters in form init and set the value but it was returning None due to some mistake. Can any one tell me where I am wrong

Updated Question

views.py

def get(self,request,category,*args,**kwargs):
    search_form = PostSearchForm()
    return render(request,self.template_name,{'search_form':search_form})

Template

<form method="get" action="." id="searchForm">
{{ search_form.keyword }}     # When searched then the value should be searched term
{{ search_form.categories }}
</form>

URL

http://example.com/?keyword=test

In the form I need to show test as value

Upvotes: 2

Views: 1456

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599630

Nothing can get into an object unless you pass it there. If you want the request in your object, then pass it:

search_form = PostSearchForm(request=request)

However this will not help you in any way at all and I'm confused about why you thought it would. If you want to pass in initial data for your form, do that:

search_form = PostSearchForm(initial={'categories': categories, 'keyword': keyword})

Upvotes: 1

Related Questions