使用图片而不显示文本的Django ChoiceField [英] Django choicefield using pictures instead of text not displaying
问题描述
我正在尝试做一些应该很简单的事情,但是我无法使其正常工作.
I'm trying to do something which should be straightforward, but I cannot have it work properly.
我想在网格中显示图像,比如说每列4-6张图像,并且能够选择其中一个然后点击提交按钮.
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.
我的模型如下:
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
我的表单如下:
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())
我的视图如下:
def mypicture(request):
form = MyPictureForm(request.POST or None)
if form.is_valid():
#TODO
return render(request, 'myproj/picture.html', {'form': form})
最后是我的hmtl(我认为问题出在哪里):
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.
我确信该错误是在html中,但是尽管我做了很多尝试,但我仍无法弄清错误所在.
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! :)
最佳:
埃里克
推荐答案
您没有在HTML中创建select元素.
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>
这篇关于使用图片而不显示文本的Django ChoiceField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!