2

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

5
  • Maybe you should show where you are using the form. Are you actually passing the request? (Although I can't see why you need it; you're not using it, and the way to do what you want is to pass in initial anyway.) Commented Oct 17, 2016 at 16:50
  • @DanielRoseman updated question please check Commented Oct 17, 2016 at 17:46
  • Well I can't understand how you're expecting this to work. You're clearly not passing request to the form, so how is it supposed to get into that method? Commented Oct 17, 2016 at 17:48
  • @DanielRoseman so how can I pass the request to the form Commented Oct 17, 2016 at 17:59
  • @DanielRoseman updated question with URL hope that should give much clarity Commented Oct 17, 2016 at 18:01

1 Answer 1

1

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})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.