从Django中的数据库中选择选择表单选项

时间:2016-05-25 06:22:02

标签: django

我正在创建一个简单的2页网站,允许用户在首页上使用下拉框或HTML选择表单(制作,模型,修剪)来获取有关将存储在数据库中的汽车的信息。按下搜索按钮后,用户将被带到提供车辆信息的页面。关于如何将这些下拉框链接到Django数据库中的数据,我感到非常困惑。

我的cardetails应用程序的models.py中的Car模型到目前为止看起来像这样:

class Car(models.Model):

    make = models.CharField(max_length=50)
    model = models.CharField(max_length=50)
    trim = models.CharField(max_length=50)

    # other info here.

    # Return the actual name of the car instead of "model-object"
    def __str__(self):
        return self.make + " " + self.model + " " + self.trim

谷歌搜索让我采用这种方式设置一个ModelForm,它位于主页应用的forms.py中:

from django import forms
from cardetails.models import Car

class CarForm(ModelForm):
    allCars = forms.ModelChoiceField(queryset=Car.objects.all())

在我拥有的3个下拉框中,“make”的下拉框在主页的html模板中看起来如此:

                <span style="display:inline-block">
                <select class="form-control" id="make">
                    {% for car in allCars %}
                    <option>{{ car.make }}</option>
                    {% endfor %}
                </select>
                <label for="make" style="display:block">Make</label>
            </span>

视图为:

from django.shortcuts import render

    def index(request):
    return render(request, 'search/index.html')

但是,“make”下拉框中没有任何内容。我想要做的是使用下拉框可以选择数据库中所有汽车的所有品牌,型号和装饰。

1 个答案:

答案 0 :(得分:1)

您可以获取所选汽车的PK或ID,并将其传递到您希望用户所在的下一个视图:

  

在你的template.html中

<form method='post' action=''>
    <select class="form-control" id="make" name='selected_car'>
        {% for car in allCars %}
            <option value='{{car.id}}'>{{ car.make }}</option>
        {% endfor %}
    </select>
</form>
  

在你的view.py

查看template.html
def allCars(request):
     .....your code here to get all car....
    if request.POST:
        car_id = request.POST['selected_car']
        redirect('name-url',car_id=car_id)


查看car_detail.html
def carDetails(request,car_id):
    selected_car = Car.objects.get(pk=car_id)
    context = {}
    template = 'car_detail.html'
    render(request, template, context)

希望这会对你有所帮助。

相关问题