Django choicefield using pictures instead of text

2019-08-26 15:52发布

I'm trying to do something which should be straightforward, but I cannot have it work properly.

I would like to display images in a grid, with let's say 4-6 images per column and be able to select one and then hit a submit button.

My model looks like:

class MyPicture(models.Model):
    name = models.CharField(max_length=60,
                            blank=False,
                            unique=True)
    logo = models.ImageField(upload_to='logos')

    def __str__(self):
        return self.name

My form looks like:

class MyPictureForm(forms.Form):

    def __init__(self, data, *args, **kwargs):
        super(MyPictureForm, self).__init__(data, *args, **kwargs)
        self.fields['pictures'] = forms.ModelChoiceField(queryset=MyPicture.objects.all())

My view looks like:

def mypicture(request):
    form = MyPictureForm(request.POST or None)

    if form.is_valid():
        #TODO

    return render(request, 'myproj/picture.html', {'form': form})

and finally, my hmtl (where I assume the issue lies):

<form action="{% url 'mypicture' %}" method="post">

    {% csrf_token %}
    {% for s in form.pictures %}
        <option value="{{ s.id }}"><img src="{{ MEDIA_URL }}{{ s.logo.url }}"/></option>      
    {% endfor %}


    <input type="submit" value="Submit" class="btn btn-primary"/>

</form>

The pictures just don't show up. When I put a breakpoint, in the form I was able to double check that the adresses of the pictures were properly selected.

I'm convinced the error is in the html, but I could not figure out where despite my many attempts.

Maybe with a fresh eye, you'll spot it in seconds... hope so! :)

Best:

Eric

2条回答
神经病院院长
2楼-- · 2019-08-26 16:46

Where did you defined pictures field in form? Or is your form a forms.ModelForm instead of forms.Form? I think you should put that outside __init__, or maybe we are missing some part of code.

class MyPictureForm(forms.Form):
    pictures = forms.ModelChoiceField(queryset=MyPicture.objects.all())
查看更多
The star\"
3楼-- · 2019-08-26 16:46

you not create a select element in your HTML.

<form action="{% url 'mypicture' %}" method="post">

    {% csrf_token %}
    <select name='picture'>
    {% for s in form.pictures.queryset %}
        <option value="{{ s.id }}"><img src="{{ MEDIA_URL }}{{ s.logo.url }}"/></option>      
    {% endfor %}
    </select>


    <input type="submit" value="Submit" class="btn btn-primary"/>

</form>
查看更多
登录 后发表回答