Python 如何在Django中添加显示下拉字段

Python 如何在Django中添加显示下拉字段,python,html,django,forms,Python,Html,Django,Forms,我正试图在Django的博客文章模型中添加一个类别字段。当我用管理面板发表文章时,它会在下拉列表中显示选项,但是我希望用html显示选项 以下是我的HTML文件中的表单: <div class="container"> <div class="row"> <div class="col-lg-7 offset-lg-1"> <form class=

我正试图在Django的博客文章模型中添加一个类别字段。当我用管理面板发表文章时,它会在下拉列表中显示选项,但是我希望用html显示选项

以下是我的HTML文件中的表单:

<div class="container">
    <div class="row">
        <div class="col-lg-7 offset-lg-1">
            <form class="create-form" method="POST" enctype="multipart/form-data">{% csrf_token %}

                <!-- title -->
                <div class="form-group">
                    <label for="id_title">Title</label>
                    <input class="form-control" type="text" name="title" id="id_title" placeholder="Title" required autofocus>
                </div>

                <!-- Body -->
                <div class="form-group">
                    <label for="id_body">Content</label>
                    <textarea class="form-control" rows="10" type="text" name="body" id="id_body" placeholder="Put the description of your post here..." required></textarea>
                </div>

        <div class="form-group">
          <label for="id_category">Category</label>
          <select class="form-control"  name="category" id="id_category" required></select>
        </div>

                <!-- Image -->
                <div class="form-group">
                    <label for="id_image">Image</label>
                    <input  type="file" name="image" id="id_image" accept="image/*" required>
                </div>

{%csrf_令牌%}
标题
内容
类别
形象

我还在StackOverflow中询问了关于Django的这类问题。然而,作为一个新手,很难向有经验的人解释你的问题,所以我不仅会回答你的问题,而且我想告诉你解决问题的方法

我认为你的问题有多个部分。这不仅仅是为了创建一个包含HTML选项的下拉列表,而且还需要在Django中传递博客文章模型中的数据

首先,假设HTML文件的名称是posts.HTML。在posts.html中,在html中创建下拉列表如下;(假设您的类别为零、一和二,您可以在管理面板的下拉列表中看到这些类别)

我希望对于Django的新手,我可以简单地解释一下。继续学习


祝你好运

你说你正在使用django,那么为什么不试试djangowell的小部件呢?你可以从bootstap获取下拉列表的帮助,链接到这里-->如果你想要django的列表,那么你可以在模型中使用元组,如图所示(例如,请参见person模型),我们是否也可以在URLquick中创建视图(在本例中为def get_posts),您还需要将其URL添加到URL.py。谢谢你的召回。
<select name="post_categories" class="filter-selectbox">
<option value="zero">"Zero"</option>
<option value="one">"One"</option>
<option value="two">"Two"</option></select>
<select name="post_categories" class="filter-selectbox">
{% for post in posts %}
    <option value="{{ post.category }}">{{ post.category }}</option>
{% endfor %} </select>
def get_posts(request):
    posts = Post.objects.all() # In this case, I assume that I can reach category as post.category in the template
    context = {"posts": posts}
    return render(request, "posts.html", context)