gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:16:28 26 4
gpt4 key购买 nike

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

内容模型.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)

内容形式.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 字段中的图像选择不同的布料。

非常感谢,帕特里克

最佳答案

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

https://github.com/applegrew/django-select2 有一个 Django 包

关于Django - 以 ManytoMany 形式显示图像字段而不是标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35274095/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com