Django - 以ManytoMany形式显示图像字段而不是标题

时间:2016-02-08 16:09:13

标签: django forms many-to-many django-crispy-forms imagefield

我正在开发一个带有脆形的Django项目。 我想使用图像而不是默认的模型标题/标签来选择多对多关系形式的实例。

内容models.py:

class Cloth(models.Model):
    owner = models.ForeignKey(settings.AUTH_USER_MODEL)
    title = models.CharField(max_length=200)

    picture = ImageCropField(upload_to='cloth_pics/%Y-%m-%d/',
                                blank=True)

    def __str__(self):
        return self.title


class Outfit(models.Model):
    owner = models.ForeignKey('profiles.Profile')
    title = models.CharField(max_length=200)
    cloths=models.ManyToManyField(Cloth)

内容forms.py

class ClothForm(forms.ModelForm):

    class Meta:
        model = Cloth
        fields = ('title','type','picture')



class OutfitForm(forms.ModelForm):

    class Meta:
        model = Outfit
        exclude= ["owner"]

内容views.py

def outfits_new(request):
    if request.method == "POST":
        form = OutfitForm(request.POST)
        if form.is_valid():
            outfit = form.save(commit=False)
            outfit.owner = get_user(request)
            outfit.created_date = timezone.now()
            outfit.save()
            pk=outfit.id
            return HttpResponseRedirect(reverse('outfit_edit_delete', args=[pk]))
    else:
        cloths = Cloth.objects.filter(owner=request.user.id)
        form = OutfitForm()
    return render(request, '../templates/outfits_new.html', {'form': form, "cloths":cloths})

内容outfits_new.html

<form enctype="multipart/form-data" method="post">
        {% csrf_token %}
        {{ form|crispy }}

        <div class="btn-group" role="group" aria-label="Basic example">

        <input type="submit" value="Submit" name="edit" class="btn btn-success">
        </div>

此代码生成一个Outfit表单,我可以在其中选择不同的布料(显示布料标题)。我想使用cloths.picture字段中的图像选择不同的布料。

非常感谢, 帕特里克

1 个答案:

答案 0 :(得分:0)

https://select2.github.io/examples.html查看select2。它允许你在组合框中做图像

https://github.com/applegrew/django-select2

有一个Django包