我在做什么? 我在一个简单的应用程序上进行培训,在这个应用程序中,人们可以订购披萨并选择他的浇头,一旦提交表单,它就会在模板文件中显示提交的查询。
有什么问题? 我很难从模板文件的表单中显示选中的复选框。
以下是我的文件:
models.py
class PickedDatas(models.Model):
name = models.CharField(max_length=255, blank=True, null=True)
class Picked(models.Model):
name = models.CharField(max_length=255)
picked = models.ManyToManyField(PickedDatas, blank=True)
forms.py
class CustomChoiceField(forms.ModelMultipleChoiceField):
def label_from_instance(self, obj):
return mark_safe('%s' % (obj.name))
class SomeForm(forms.ModelForm):
class Meta:
model = Picked
fields = ['name', 'picked']
picked = CustomChoiceField(queryset=PickedDatas.objects.all(), widget=forms.CheckboxSelectMultiple())
views.py
def some_view(request):
if request.method == 'POST':
form = SomeForm(request.POST)
if form.is_valid():
...
else:
form = SomeForm
return render(request, 'features.html', {'form':form, 'picked':Picked.objects.all()})
对于模板文件,我使用for循环显示Picked models数据。
我如何实现我想要做的事情?
编辑
此处是模板文件 features.html
<h2>Enter your name and choose your pizza toppings</h2>
<form method='post'>
{% csrf_token %}
{{ form.as_p }}
<input type='submit' value='submit'>
</form>
{% for p in picked %}
<h2>Pizza For : <strong>{{ p.name }}</strong></h2>
<p>{{ p.picked }}</p>
{% endfor %}
它为{{p.picked}}提供了这个:pizza.PickedDatas.None
答案 0 :(得分:1)
Picked.picked
是一个多对多字段,因此您需要遍历选项:
{% for picked in picked %}<!-- Note renamed variable to prevent clash with inner loop -->
<h2>Pizza For : <strong>{{ picked.name }}</strong></h2>
<p>{% for p in picked.picked.all %}{{ p }}{% endfor %}</p>
{% endfor %}