简体   繁体   English

如何从外键模型填充Django中的下拉列表

[英]how to populate dropdown list in Django from a foreignkey model

I have two models. 我有两个型号。

class ArticleCategory(models.Model):
    category = models.CharField(max_length=255,blank=False)

class Article(models.Model):
    title = models.CharField(max_length=255,blank=False)
    body = models.TextField()
    pub_date = models.DateTimeField(auto_now_add=True)
    category = models.ForeignKey(ArticleCategory,default=1)

Now I have to render a template and save the form for Article model. 现在我必须渲染一个模板并保存文章模型的表单。 I have a foreignKey field in my Article Model and because of that I'm not able to save my article form. 我的文章模型中有一个foreignKey字段,因此我无法保存我的文章形式。 I want to select a category from dropdown list and save it in my Article model. 我想从下拉列表中选择一个类别并将其保存在我的文章模型中。

How should I code my template for this ? 我应该如何为此编码模板?

My views.py function for this is: 我的views.py函数是:

def create(request):
    if request.POST:
        form = ArticleForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/articles/all/')
    else:
        form = ArticleForm()
        args={}
        args.update(csrf(request))
        args['categories'] = ArticleCategory.objects.all()
        args['form'] = form
        return render_to_response('create_article.html', args)

My template create_article.html currently looks like this: 我的模板create_article.html目前看起来像这样:

<form role="form" action="/articles/create/" method="POST" enctype="multipart/form-data">{% csrf_token %}
                        <div class="row">
                            <div class="form-group col-lg-3">
                            <label></label>
                                <p>{{form.title}}</p>
                            </div>
                            <div class="form-group col-lg-3">
                                <label>Category</label>
                                <p>
                                    <select id="id_category">
                                        {% for category in categories  %}
                                        <option value="{{ category }}">{{ category.category }}</option>
                                        {% endfor %}
                                    </select>
                                </p>
                            </div>
                            <div class="clearfix"></div>
                            <div class="form-group col-lg-12">
                                <label>Body</label>
                                {{form.body}}
                            </div>
                            <div class="form-group col-lg-12">
                                <button type="submit" class="btn btn-default">Save Article</button>
                            </div>
                        </div>
                    </form>

You don't need to do this manually. 您无需手动执行此操作。 If your ArticleForm is ModelForm and doesn't exclude category field then you can just write {{ form.category }} and get dropdown created by django automatically. 如果您ArticleFormModelForm不排除category字段,那么你可以只写{{ form.category }}并获得通过下拉Django的自动创建。 It uses ModelChoiceField underneath the hood. 它使用了引擎盖下的ModelChoiceField

replace 更换

<select id="id_category">
  {% for category in categories  %}
    <option value="{{ category }}">{{ category.category }}</option>
  {% endfor %}
</select>

with

{{ form.category }}

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

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