Pass the initial value to the Django form field

Django newbie question ....

I am trying to write a search form and save the state of the input field between the search query and the search results.

Here is my form:

class SearchForm(forms.Form): q = forms.CharField(label='Search: ', max_length=50) 

And here is my views code:

 def search(request, q=""): if (q != ""): q = q.strip() form = SearchForm(initial=q) #get results here... return render_to_response('things/search_results.html', {'things': things, 'form': form, 'query': q}) elif (request.method == 'POST'): # If the form has been submitted form = SearchForm(request.POST) if form.is_valid(): q = form.cleaned_data['q'] # Process the data in form.cleaned_data return HttpResponseRedirect('/things/search/%s/' % q) # Redirect after POST else: form = SearchForm() return render_to_response('things/search.html', { 'form': form, }) else: form = SearchForm() return render_to_response('things/search.html', { 'form': form, }) 

But this gives me an error:

 Caught an exception while rendering: 'unicode' object has no attribute 'get' 

How to transfer the initial value? The various things I tried seem to interfere with the request.POST parameter.

+8
django django-forms
source share
2 answers

A few things are not very good here ...

1) The recommended thing after POST is redirection. This avoids the pop-up message that you are re-adding the form using the back button.

2) You do not need to say if request.method == 'POST' , just if request.POST . This makes it easier to read code.

3) The view usually looks something like this:

 def myview(request): # Some set up operations if request.POST: form=MyForm(request.POST) if form.is_valid(): # some other operations and model save if any # redirect to results page form=MyForm() #render your form template 

This does not mean that there cannot be much simpler and more complex representations. But this is the essence of the view: if the request processes the form and redirects it; if the request receives a visualization of the form.

I do not know why you are getting unicode error. I can only think that this is due to one of your models that you do not provide. The error, as spookylukey mentioned in his comment, is most likely due to the fact that you are sending a string instead of a dict to the original parameter.

I really recommend the django documentation in particular the tutorial. but there is also a very nice Django Book .

All that said, I think you need something like:

 def search(request, q=None): if request.POST: form = SearchForm(request.POST) if form.is_valid(): q = form.cleaned_data['q'] url=reverse('search_results', args=(q,)) return HttpResponseRedirect(url) if q is None: form = SearchForm() else: form = SearchForm(initial={'q': q}) return render_to_response('things/search.html', { 'form': form, }) 

Note that the original parameter is a type of field values ​​for your form.

Hope this helps.

+9
source share

Django forms are not particularly useful for your use case. In addition, it’s much better for the search page to use the GET form and maintain state in the URL. The following code is much shorter, simpler, and better compliant with HTTP standards:

 def search(request): q = request.GET.get('q','').strip() results = get_some_results(q) render_to_response("things/search.html", {'q': q, 'results': results}) 

Template:

 <form method="GET" action="."> <p><input type="text" value="{{ q }}" /> <input type="submit" value="Search" /></p> {% if q %} {% if results %} Your results... {% else %} No results {% endif %} {% endif %} </form> 
+5
source share

Source: https://habr.com/ru/post/639895/


All Articles