我的组合框countries(def trip_selector
)依赖于组合框trips(def trips
)。在组合框中,我正确地显示了项目。如果我点击按钮,我想打印textarea(def result
)中的所选项目。x1c 0d1x的数据
问题是我无法提取trips组合框中的所选项目,我得到错误:None
。我使用selected = request.GET.get('trips')
也是因为trips是trips.html
页面中select name="trips" id="id_trip"
的名称。要打印的选定项目不发送数据,只显示数据。我不知道为什么它不工作。你能帮帮我吗?
注意事项:我指定一个重要的事情,如果你想帮助我:我不想把selected = request.GET.get('trips')移动到def test1()函数或def result()函数中,如果需要的话,最多创建另一个函数。def test1只是我将要创建的许多函数中的一个,所以将selected = request.GET.get('trips')移动到每个函数test1、test 2、test 3、test 4等中是没有意义的。这些函数将显示在textarea(def result)中,该区域必须仅保留为查看器,因为它将显示各种函数(而不仅仅是一个)。
views.py
from django.shortcuts import render
from .models
import Trip import random
def trip_selector(request):
countries = Trip.objects.values_list('country', flat=True).distinct()
trips = [] # no trips to start with
return render(request, 'form.html', {"countries": countries, "trips": trips})
def trips(request):
country = request.GET.get('country')
trips = Trip.objects.filter(country=country)
#selected item
global selected
selected = request.GET.get('trips') #Don't move in test1() or result() §
return render(request, 'trips.html', {"trips": trips, "selected": selected})
def test1():
sentence = ["The selected trip is ", "Congratulations you have selected the trip ", "You have currently selected travel ", "The currently selected trip is "]
random_sentence = random.choice(sentence) final_sentence = random_sentence + selected return final_sentence
def result(request):
test_print_in_result = test1()
return render(request,"result.html", {"test_print_in_result":
test_print_in_result})
字符串
form.py
{% extends 'base.html' %}
{% block content %}
<!-- First Combobox -->
<label for="id_country">Country</label>
<select name="country" id="id_country" hx-get="{% url 'trips' %}" hx-swap="outerHTML" hx-target="#id_trip" hx-indicator=".htmx-indicator" hx-trigger="change">
<option value="">Please select a country</option>
{% for country in countries %}
<option value="{{ country }}">{{ country }}</option>
{% endfor %}
</select>
<!-- Second Combobox ??????? (non lo so)-->
<label for="id_trip">Trip</label> {% include "trips.html" %}
<!-- Textarea-->
{% include "result.html" %}
<!-- Button-->
<button type="button" class="mybtn" name="btn" hx-get="{% url 'result' %}" hx-swap="outerHTML" hx-target="#id_result" hx-indicator=".htmx-indicator">Button 1</button>
{% endblock %}
型
trips.html
<!-- Second Combobox -->
<select name="trips" id="id_trip" style="width:200px;">
<option value="">Please select</option>
{% for trip in trips %}
<option value="{{ trip.id }}">{{ trip.departure }}-{{ trip.destination }}</option>
{% endfor %}
</select>
型
result.html
<textarea name="result" id="id_result">{{ test_print_in_result }}</textarea>
型
我希望有人能帮助我。谢谢大家!
1条答案
按热度按时间cqoc49vn1#
如果你使用的是Django表单,你应该从表单本身获取数据(当然是POST请求)。你不能用GET请求提取数据,除非你把它们作为参数传递,比如url/path/或url/path?q=。对于第二个,您可以使用
request.GET.get()
。我希望这对你有帮助。