虽然我阅读了django文档,但是我仍然很困惑如何使用request.POST从下拉列表中获取值以查询数据库。以及如何将所选值的详细信息返回到前端以显示结果?
假设我可以在下拉框中选择“区域”,它将返回该区域类别下该餐厅的详细信息
class Restaurant(models.Model):
restId = models.AutoField(db_column='restId', primary_key=True)
restName = models.TextField(db_column='restName')
phone = models.IntegerField()
address = models.TextField()
ratings = models.DecimalField(max_digits=2, decimal_places=1)
cuisine = models.TextField()
region = models.TextField()
last_modify_date = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
class Meta:
managed = True
db_table = "restaurant"
# def index_view(request):
# rest_list = Restaurant.objects.all()
# context = {
# 'rest_list': rest_list
# }
# return render(request, 'index.html', context)
def get_name(request):
# region = Restaurant.objects.all().order_by('region').values_list('region', flat=True)
if request.method == 'GET':
rest_form = RestaurantForm()
return render(request, 'index.html', {'rest_form': rest_form})
{% block content %}
<form action="" method="post">
{% csrf_token %}
<select name = "rest_value">
{% for rest in rest_form %}
<option value = {{ rest }} ></option>
{% endfor %}
</select>
<input type="submit" value="Select" name="region">
</form>
{% endblock %}
from django.forms import ModelForm
from .models import Restaurant
class RestaurantForm(ModelForm):
class Meta:
model = Restaurant
fields = ['region']
答案 0 :(得分:1)
要在问题中提供答案,可以使其与以下代码一起使用( note:未经测试);但请参阅底部的注释:
Python视图:
def index_view(request):
selected_region = None
restaurants = Restaurant.objects.all()
if request.method == "POST":
# Filter restaurants by selected region, but only on a POST
selected_region = request.POST.get("region")
restaurants = restaurants.filter(region=selected_region)
# Get a list of all unique regions (group by region)
regions = Restaurant.objects.order_by('region').values_list('region', flat=True)
context = {
'regions': regions,
'restaurants': restaurants,
'selected_region': selected_region
}
return render(request, 'index.html', context)
Django模板:
<h1>Index</h1>
<form method="post">
<select name="region">
{% for region in regions %}
<option
value="{{ region }}"
{% if selected_region == region %}
selected="selected"
{% endif %}
>{{ region }}</option>
{% endfor %}
</select>
<input type="submit" value="Select">
</form>
{% if selected_region %}
<p>
Nice, you selected: {{ selected_region }}!
</p>
<p>
Restaurants in this region:
</p>
<ul>
{% for restaurant in restaurants %}
<li>{{ restaurant.restName }}</li>
{% endfor %}
</ul>
{% endif %}
一些要点:
action
命名为“ selectRegion”。这会将其发布到其他URL。在我的示例中,我从表单中删除了action
,以便将其发布回与index.html
相同的URL。region
中将Restuarant
用作外键。