更新Form.intial不会改变Django模板中的初始值

目标

我想在搜索结果呈现时保留查询。下面是一个示例,其中搜索栏在结果页面上包含堆栈溢出。


失败的解决方案

这些是最小的代码示例


# search_results.html

<form action="/search" method="post">

    {% csrf_token %}

    {{ form }}

    <input type="submit" value="Search">

</form>

# views.py

...

class SearchView(TemplateView):

    """Search view"""

    def form_valid(self, form):

        """redirect to the success url with url params"""

        quoted_user_query = urllib.parse.quote_plus(form.cleaned_data['user_query'])

        return HttpResponseRedirect(''.join([self.get_success_url(), quoted_user_query]))


    def get_context_data(self. **kwargs):

        context = super().get_context(**kwargs)

        user_query = self.request.GET.get('q', None)

        form.initial = {'user_query': user_query}

        return context


    def get_success_url(self):

        """append success url with search query"""

        if not self.success_url:

            raise ImproperlyConfigured('No success url for {}'.format((str(self))))

        return ''.join([str(self.success_url), '?q='])

我第一次在浏览器中搜索时,模板按预期呈现。如果我搜索以下内容将呈现foo


<form action="/search" method="post">

    <input type="text" value="foo" name="search">

    <input type="submit" value="Search">

</form>


但是,第二次搜索不会更改搜索栏中的字符串。如果我在搜索后搜索,搜索栏的值不会更改为预期。barfoobar


<form action="/search" method="post">

    <input type="text" value="foo" name="search">

    <input type="submit" value="Search">

</form>


我做错了什么?下面是表单代码。


# forms.py

from django import forms



class SearchBar(forms.Form):

    user_query = forms.CharField()

编辑:当我将 {{ form.initial.user_query }} 添加到模板时,预期值呈现为搜索栏旁边的文本,但不呈现在搜索栏中。


# search_results.html

{{ form.initial.user_query }}

<form action="/search" method="post">

    {% csrf_token %}

    {{ form }}

    <input type="submit" value="Search">

</form>

bar

<form action="/search" method="post">

    <input type="text" value="foo" name="search">

    <input type="submit" value="Search">

</form>


慕森王
浏览 59回答 2
2回答

一只甜甜圈

我发现了一个笨拙的解决方案,可以创建表单的新实例,而不是更新属性initial# views.py...class SearchView(TemplateView):&nbsp; &nbsp; """Search view"""extra_context = {'form': SearchBar()}&nbsp; &nbsp; def get_context_data(self. **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; context = super().get_context(**kwargs)&nbsp; &nbsp; &nbsp; &nbsp; user_query = self.request.GET.get('q', None)&nbsp; &nbsp; &nbsp; &nbsp; if user_query is not None:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; context['form'] = self.form_class(data={'user_query': user_query})&nbsp; &nbsp; &nbsp; &nbsp; return context...

慕码人2483693

我不认为你得到任何值与,因为输入字段的名称在表单中。所以试试这个:self.request.GET.get('q', None)user_queryclass SearchView(TemplateView):&nbsp; &nbsp; """Search view"""&nbsp; &nbsp; def get_context_data(self. **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; context = super().get_context(**kwargs)&nbsp; &nbsp; &nbsp; &nbsp; user_query = self.request.GET.get('user_query', None)&nbsp; &nbsp; &nbsp; &nbsp; context['form'] = SearchBar(initial = {'user_query': user_query})&nbsp; &nbsp; &nbsp; &nbsp; return context同时将表单方法从 post 更改为 get ie<form method='get' action='/search'>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python