简体   繁体   English

使用Django从模型创建下拉菜单

[英]Creating Dropdown Menu from Model using Django

I tried searching for suggestions on how to solve my problem, but wasn't finding exactly what I was looking for. 我尝试寻找有关如何解决问题的建议,但没有找到我想要的东西。 So, sorry if this has been covered before. 因此,对不起,如果以前已经讨论过。

I need to create a new class within existing models.py file to add a new table to an existing database, add code to the existing views.py file to render to a form, and use the existing view.html file to be able to display a dropdown menu that shows all the values in the model and allows the user to select one of those values. 我需要在现有的models.py文件中创建一个新类,以将新表添加到现有数据库,将代码添加到现有的views.py文件中,以呈现为表单,并使用现有的view.html文件来实现显示一个下拉菜单,该菜单显示模型中的所有值,并允许用户选择这些值之一。

So, I created the table within models.py and need to figure out where to go from here. 因此,我在models.py中创建了表格,需要弄清楚从这里开始的去向。 It looks similar to this: 它看起来类似于:

models.py models.py

class PhoneTable(models.Model):

    phone_number = PhoneNumberField(primary_key=True, max_length=20)
    call_type = models.CharField(choices=CALL_TYPES, max_length=10)
    profile = models.CharField(null=True, blank=True, max_length=4)
    extension = models.ForeignKey(Profile, related_name='extension', max_length=4)

Any advice or direction would be greatly appreciated. 任何建议或指示将不胜感激。 If I missed information that would be helpful that I should provide please let me know. 如果我错过了应该提供的有用信息,请告知我。

Thank you. 谢谢。

  1. Write a new view in views.py 在views.py中写一个新视图
  2. Create a new form class with a ChoiceField 使用ChoiceField创建一个新的表单类
  3. Populate this ChoiceField with the data from your database via PhoneTable.objects.all() 通过PhoneTable.objects.all()使用数据库中的数据填充此ChoiceField。
  4. Create a template, say phoneview.html 创建一个模板,例如phoneview.html
  5. Render this template from your view and send the form as a template parameter 从您的视图中渲染此模板,并将表单作为模板参数发送

If you don't know how to do these things read Django app tutorial 如果您不知道该怎么做,请阅读Django应用教程

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

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