3

I am working on a Django project with crispy forms. I want to use images instead of the the default Models title/label to select a instance in a Many to Many relation form.

Content 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)

Content forms.py

class ClothForm(forms.ModelForm):

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



class OutfitForm(forms.ModelForm):

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

Content 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})

Content 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>

This code produces a Outfit form where I can select different cloths( displaying the cloths title). I want to select different cloths using a image from the cloths.picture field.

Thank you very much, Patrick

1 Answers1

0

Have a look at select2 at https://select2.github.io/examples.html. It allows you to do images in comboboxes

There is a Django package at https://github.com/applegrew/django-select2

Thomas Turner
  • 2,722
  • 1
  • 27
  • 23