Django外键下拉

时间:2015-03-22 15:57:45

标签: django forms drop-down-menu foreign-keys

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 个答案:

答案 0 :(得分: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)