将初始值传递给Django表单字段

时间:2021-08-05 19:19:40

Django newbie question....

Django新手问题....

I'm trying to write a search form and maintain the state of the input box between the search request and the search results.

我正在尝试编写搜索表单并维护搜索请求和搜索结果之间的输入框状态。

Here's my form:

这是我的表格:

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

And here's 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 the error:

但这给了我错误:

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

How can I pass the initial value? Various things I've tried seem to interfere with the request.POST parameter.

我怎样才能传递初始值?我尝试过的各种事情似乎都干扰了request.POST参数。

2 个解决方案

#1


10  

Several things are not good here...

有些事情在这里不好......

1) The recommended thing after a POST is to redirect. This avoids the infamous popup saying that you are resubmitting the form when using the back button.

1)POST后推荐的东西是重定向。这避免了臭名昭着的弹出窗口,表示您在使用后退按钮时重新提交表单。

2) You don't need to say if request.method == 'POST', just if request.POST. That makes your code easier to read.

2)你不需要说request.method =='POST',就像request.POST一样。这使您的代码更容易阅读。

3) The view generally looks something like:

3)视图通常看起来像:

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

That is not to say that there can't be much simpler and much more complicated views. But that is the gist of a view: if request is post process the form and redirect; if request is get render the form.

这并不是说不可能有更简单和更复杂的观点。但这是一个观点的要点:如果请求是后期处理表单和重定向;如果请求获得渲染表单。

I don't know why you are getting an unicode error. I can only think that it is related to one of your models that you don't provide. The error, as spookylukey mentions is in his comment, most likely is caused by you submitting a string instead of a dict to the initial parameter.

我不知道你为什么会收到unicode错误。我只能认为它与您未提供的某个型号有关。像spookylukey提到的那个错误在他的评论中,很可能是由你提交字符串而不是dict到初始参数引起的。

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

我真的推荐django文档,特别是教程。但是也有非常好的Django Book。

All that said, I think you want 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,
    })

Notice that the parameter to initial is a dict of the field values of your form.

请注意,initial的参数是表单字段值的字典。

Hope that helps.

希望有所帮助。

#2


5  

Django forms are not particularly helpful for your use case. Also, for a search page, it's much better to use a GET form and maintain state in the URL. The following code is much shorter, simpler and conforms far better to HTTP standards:

Django表单对您的用例不是特别有用。此外,对于搜索页面,使用GET表单并在URL中维护状态要好得多。以下代码更短,更简单,并且更符合HTTP标准:

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

The 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>

#1


10  

Several things are not good here...

有些事情在这里不好......

1) The recommended thing after a POST is to redirect. This avoids the infamous popup saying that you are resubmitting the form when using the back button.

1)POST后推荐的东西是重定向。这避免了臭名昭着的弹出窗口,表示您在使用后退按钮时重新提交表单。

2) You don't need to say if request.method == 'POST', just if request.POST. That makes your code easier to read.

2)你不需要说request.method =='POST',就像request.POST一样。这使您的代码更容易阅读。

3) The view generally looks something like:

3)视图通常看起来像:

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

That is not to say that there can't be much simpler and much more complicated views. But that is the gist of a view: if request is post process the form and redirect; if request is get render the form.

这并不是说不可能有更简单和更复杂的观点。但这是一个观点的要点:如果请求是后期处理表单和重定向;如果请求获得渲染表单。

I don't know why you are getting an unicode error. I can only think that it is related to one of your models that you don't provide. The error, as spookylukey mentions is in his comment, most likely is caused by you submitting a string instead of a dict to the initial parameter.

我不知道你为什么会收到unicode错误。我只能认为它与您未提供的某个型号有关。像spookylukey提到的那个错误在他的评论中,很可能是由你提交字符串而不是dict到初始参数引起的。

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

我真的推荐django文档,特别是教程。但是也有非常好的Django Book。

All that said, I think you want 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,
    })

Notice that the parameter to initial is a dict of the field values of your form.

请注意,initial的参数是表单字段值的字典。

Hope that helps.

希望有所帮助。

#2


5  

Django forms are not particularly helpful for your use case. Also, for a search page, it's much better to use a GET form and maintain state in the URL. The following code is much shorter, simpler and conforms far better to HTTP standards:

Django表单对您的用例不是特别有用。此外,对于搜索页面,使用GET表单并在URL中维护状态要好得多。以下代码更短,更简单,并且更符合HTTP标准:

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

The 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>