简体   繁体   English

Django views.py:无法在 function 之外使用变量

[英]Django views.py : unable to use vriable outside function

I want a new page to open when a django form is filled- by hitting enter/by clicking on the 'Search' input and display results in that page using the data entered in the form.我希望在填写 django 表单时打开一个新页面 - 通过点击输入/单击“搜索”输入并使用表单中输入的数据在该页面中显示结果。

forms.py: forms.py:

class SearchBar(forms.Form):
    Search = forms.CharField(label='', max_length=100, widget=forms.TextInput)

The HTML page with the form looks like: HTML 页面如下所示:

index.html索引.html

<form class="" action="result" method="post">
          
          {% csrf_token %}
          {{ form1.as_table }}

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

</form>

I want the submission of this form to open a new page: result.html我想提交这个表单打开一个新页面: result.html

I have set the url of 'result' to the said HTML page:我已将“结果”的 url 设置为所述 HTML 页面:

urls.py网址.py

urlpatterns=[
    path('result', views.result, name='result'),
]

I have extracted the data entered in the from by form1.cleaned_data['Search'] .我已经提取了form1.cleaned_data['Search']在 from 中输入的数据。

form_input=form1.cleaned_data['Search']

However, once the result page is opened, it shows that the data (form_input) is not defined.但是,一旦打开结果页面,就会显示数据(form_input)未定义。 The following error is shown:显示以下错误:

name 'form_input' is not defined

I am unable to use this data (form_input) in any other function of the views.py file.我无法在views.py文件的任何其他 function 中使用此数据(form_input)。

views.py视图.py

def index(request):
    form1 = forms.SearchBar()
    if request.method == "POST":
        form1 = forms.SearchBar(request.POST)
        if form1.is_valid():
            global form_input
            form_input= (form1.cleaned_data['Search'])

def result(request):
    print(form_input)

I don't understand why this is happening.我不明白为什么会这样。 I have even declared the variable form_input as a global variable.我什至将变量form_input声明为global变量。

You will have to do something like this:你将不得不做这样的事情:

views.py视图.py

from . forms import SearchBar

def search_view(request):
    if request.method == "POST":
        form = SearchBar(request.POST)
        if form.is_valid():
            form_input = form.cleaned_data['Search']
            search_result = # your search query using the form_input variable
            return render(request, "result.html", {"search_result ": search_result })

If I understand corectly you would like to have your search bar in the base.html (base template that all other templates inherit from) then where your search bar in the template would be write something like this:如果我正确理解您希望将搜索栏放在base.html (所有其他模板继承自的基本模板)中,那么您在模板中的搜索栏将是这样写的:

<form action={% url 'search_view' %} method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Search</button>
</form>

And the result.html would look like this:结果.html看起来像这样:

{% for item in search_result %}
    {{ i.name }}
{% endfor %}

UPDATE更新

Well, obviously the purpose of a search bar is to filter and display objects of a given model/models, for example if you had a User model:好吧,显然搜索栏的目的是过滤和显示给定模型的对象,例如,如果您有一个User model:

class User(models.Model):
    name = models.CharField(max_length=50)
    is_active = models.BooleanField(default=True)

and wanted to filter objects based on your user.name then the the line of code would look something like this:并想根据您的user.name过滤对象,那么代码行将如下所示:

search_results = User.objects.filter(name__contains=form_input)

So that if you had for example 3 users with names like Tom Jablinski , Tommy Joe and Jack White (for example) and searched for Tom you would get a queryset containing 2 user objects: Tom Jablinski and Tommy Joe and they would be displayed in result.html temaplte.因此,如果您有例如 3 个名称为Tom JablinskiTommy JoeJack White的用户(例如)并搜索Tom ,您将得到一个包含 2 个用户对象的查询集: Tom JablinskiTommy Joe ,它们将显示在result.htmlresult.html模板。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM