Django外键下拉

Posted

技术标签:

【中文标题】Django外键下拉【英文标题】:Django foreign key drop down 【发布时间】:2015-05-25 15:11:05 【问题描述】:

刚接触 Django 和 Python,我需要一些关于外键下拉菜单的帮助。基本上,我有一个类别模型和一个图像模型,我希望用户能够选择将图像放入哪个类别。如何在图像表单中为类别创建下拉列表?我的观点和 html 也正确吗?我在网上看过,但我自己似乎无法做到。我不断收到错误。

这是我的模型:

class Images(models.Model):
    image = models.ImageField(upload_to='images', blank=False)
    img_name = models.CharField(max_length=120, blank=True)
    img_date = models.DateTimeField(default=now())
    img_user = models.ForeignKey(User)
    img_cat_id = models.ForeignKey(Categories)

    def __unicode__(self):
        return self.img_name

class Categories(models.Model):
    cat_descr = models.CharField(max_length =120, blank=False)

    def __unicode__(self):
       return self.cat_descr

观看次数:

@login_required
def upload_images(request):
    context = RequestContext(request)
    context_dict=

    if request.method == 'POST':  # render the form, and throw it back.
        # take the form data and process it!

        form = UploadImagesForm(request.POST, request.FILES)

        if form.is_valid():
            print 'form is_valid'


            upload_image = form.save(commit=False)
            upload_image.img_user = request.user

            if 'image' in request.FILES:
                upload_image.image  =request.FILES['image']

            upload_image.save()

            return render(request, 'rmb/upload.html', 'upload_image': form)

        else:
            print form.errors

    # Not a HTTP POST, so we render our form using two ModelForm instances.
    # These forms will be blank, ready for user input.
    else:
        form = UploadImagesForm()

        context_dict = 'upload_image': form
        all_categories = Categories.objects.order_by('-id')
        context_dict['all_categories'] = all_categories
        print context_dict

        return render_to_response('rmb/upload.html', context_dict, context)

表格:

class UploadImagesForm(forms.ModelForm):

#cat_list = ModelChoiceField(queryset=Categories.objects.all())

class Meta:
    model = Images
    fields=('image','img_name')

HTML:

% block body_block %
    <form id="upload_form" method="post" action="/rmb/upload/"
            enctype="multipart/form-data">

            % csrf_token %
              upload_image.as_table 
            <input type="submit" name="submit" value="Upload" />
     % for categories in all_categories %

         <div>  categories.id  </div>
          categories.cat_descr 
         <input type="submit" name="submit" value="Upload" />
      % endfor %


    </form>
% endblock %

【问题讨论】:

“我不断收到错误。”什么样的错误? 另外,您的代码缩进不正确,导致故障排除非常困难。 【参考方案1】:

You don't need to insert the HTML for the form manually, just use form in the template.

% block body_block %
    <form id="upload_form" method="post" action="/rmb/upload/"
            enctype="multipart/form-data">

            % csrf_token %
             form 
    </form>
% endblock %

By default a ForeignKey will be a select field 所以你不需要做太多其他事情。


顺便说一句,给您的模型和字段起更合适的名称。我们知道这些都是图像字段,因为它们在图像上并且确保,除非您的模型是事物的集合,否则您给它一个单数名称。最后,当使用外键时,项目会获得一个额外字段 fieldname_id,这只是 ID,而 fieldname 也是提供相关项目的属性。

所以而不是:

class Images(models.Model):
    image = models.ImageField(upload_to='images', blank=False)
    img_name = models.CharField(max_length=120, blank=True)
    img_date = models.DateTimeField(default=now())
    img_user = models.ForeignKey(User)
    img_cat_id = models.ForeignKey(Categories)

用途:

class Image(models.Model):
    image = models.ImageField(upload_to='images', blank=False)
    name = models.CharField(max_length=120, blank=True)
    date = models.DateTimeField(default=now())
    user = models.ForeignKey(User)
    category = models.ForeignKey(Categories)

【讨论】:

以上是关于Django外键下拉的主要内容,如果未能解决你的问题,请参考以下文章

Django admin禁用外键下拉但保留添加按钮旁边

外键 id 无法加载到 Django 模板的下拉列表中

如何在 django admin change_form 中更改外键字段的顺序

python测试开发django-37.外键(ForeignKey)查询

如何在表单完成期间设置外键(python/django)

如何在 Django 中向 ModelForm 添加外键字段?