如何将模型数据库的数据填充到Django的dropdownlist中

时间:2019-02-13 08:41:00

标签: django database django-models dropdown

我正在尝试将数据库中的现有数据填充到一个下拉列表中 我只想让数据出现在dropownlist内。

当我运行系统时,它显示以下错误:

  / testmodel3上的

DoesNotExist匹配查询不存在。请求   方法:POST请求URL:http://127.0.0.1:8000/ Django版本:2.1.7   异常类型:DidsNotExist异常值:testmodel3匹配   查询不存在。

它表示错误在第14行

tmn3 = testmodel3.objects.get(name = tmn) 
  1. 我在models.py中创建类
  2. 在url.py中映射页面
  3. 创建表单
  4. 创建模板
  5. 在views.py中创建一个函数。

models.py

class testmodel3(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return str(self.name)

url.py

from django.contrib import admin
from django.urls import path
from.views import *

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', home),

]

forms.py

from django import forms
from .models import *

class drodownForm(forms.ModelForm):

    class Meta:
        model = testmodel
        fields = ('name',)

home.html

    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
    </head>
    <body>

    <form method="POST">{% csrf_token %}
        <table>
            <tr><td>mouhafazat name:</td>
                <td>
                    <select name = "dropdwn1">
                        {% for testmodel in testmodel3name %}
                            <option value="{{ testmodel3.name }}">{{ testmodel3.name }}</option>
                        {% endfor %}
                    </select>
                </td>
                <td><input type="submit" value="click" /></td>
            </tr>
        </table>


</form>

</body>
</html>

views.py

from django.shortcuts import render
from django.http import HttpResponse
from testapp.models import *
from testapp.forms import drodownForm


def home(request):
    testmodel3name = testmodel3.objects.all()
    print(testmodel3name)
    tmn = request.POST.get('dropdwn1')
    if request.method =='GET':
        form = drodownForm()
    else:
        tmn3 = testmodel3.objects.get(name = tmn)
        print("test for dropdown")

    return render(request,'./home.html',{'form': form, 'testmodel3name': testmodel3name})

我希望在下拉列表中查看存储的数据

0 个答案:

没有答案