Django表单许多Tto Many字段由外键隔离

时间:2015-09-09 06:37:26

标签: python django

models.py

class FoodType(models.Model):
food_type = models.CharField(max_length=50, default=None)

class Foods(models.Model):
foods = models.CharField(max_length=100, default=None)
food_type = models.ForeignKey(FoodType, default=1)

class FoodsChosen(AbstractTrainingCertificateDocuments):
user = models.ForeignKey(UserProfile, default=None)
foods = models.ManyToManyField(Foods, default=None)

forms.py

class FoodsForm(forms.ModelForm):
foods = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple(renderer=HorizontalCheckboxRenderer), queryset=Foods.objects.filter(), error_messages={'required': 'Please do not forget to select the foods'})
class Meta:
model = FoodsChosen
fields = ('foods', )

views.py

foods_form = FoodsForm()
context_dict['foods_form'] = foods_form
return render(request, template, context_dict)

的index.html

{% for x in foods_form.foods %}
<div class="col-md-6">
{{ certs }}
</div>
{% endfor %}

如何将多对多复选框表单小部件返回到多对多复选框表单,该表单由我的模板上的外键输入?

FRUITS
“复选框”苹果
“复选框”香蕉
“复选框”芒果
 
VEGETABLES
“复选框”白菜
“复选框”brocolli
“复选框”壁球  
MEAT
“复选框”牛排
“复选框”猪肉 “复选框”肉
 
而不是:
“复选框”苹果
“复选框”香蕉
“复选框”芒果
“复选框”白菜
“复选框”brocolli
“复选框”壁球 “复选框”牛排
“复选框”猪肉 “复选框”肉

1 个答案:

答案 0 :(得分:0)

你的view.py不正确

foods_form = FoodsForm()
if foods_form.isvalid():
     food = foods_form.cleaned_data['foods']
context_dict['foods_form'] = foods_form
context_dict['food'] = food
return render(request, template, context_dict)

并在index.htm

{% for x in food %}
<div class="col-md-6">
  {{ certs }}
</div>
{% endfor %}