關於此的大多數問題似乎都集中在節省m2m表。我很好奇如何從一個(或兩個組合)表單中查看中間表的字段。Django:以表格的形式顯示中間表的字段
這個想法是我有很多資源和很多餐。不同的膳食可以有相同的資源,但數量不同。說:捲餅有x磅牛肉,但法加它有y。
我想要創建一個表單來編輯捲餅餐,以便我可以查看/編輯/創建:餐的名稱,餐中的資源以及與該餐中資源相關的數量。我當前的代碼顯示一個包含所有形式,但通過M2M表與資源相關的金額
我通過中介表連接的兩個車型:
class Resource(models.Model):
name = models.CharField(max_length=200)
unit = models.ForeignKey(Unit)
units_per_pack = models.PositiveSmallIntegerField()
packs_per_case = models.PositiveSmallIntegerField()
allergens = models.ManyToManyField(Allergen, blank=True)
class Meal(models.Model):
name = models.CharField(max_length=200)
resources=models.ManyToManyField(Resource,through='MealResourceRelationship')
recipe = models.TextField(default='')
class MealResourceRelationship(models.Model):
resource = models.ForeignKey(Resource)
meal = models.ForeignKey(Meal)
units_per_person = models.DecimalField(max_digits=19,decimal_places=2)
我試圖用一個簡單的ModelForm作爲下方觀察:
class MealForm(forms.ModelForm):
class Meta:
model = Meal
fields = '__all__'
這種觀點:
def meal_edit(request, pk=None, template_name='foodstuffs/meal_edit.html'):
if id:
meal = get_object_or_404(Meal, pk=pk)
else:
meal = Meal()
if request.POST:
form = MealForm(request.POST,instance=meal)
if form.is_valid():
meal_mod = form.save(commit=False)
meal_mod.save()
# remove existing resources
meal_mod.resources.clear()
for resource in form.cleaned_data.get('resources'):
meal_resource_rel = MealResourceRelationship(meal=meal_mod,
resource=resource,
units_per_person=1)
meal_resource_rel.save()
# messages.add_message(request, messages.SUCCESS, _('Meal correctly saved.'))
# If the save was successful, redirect to another page
redirect_url = reverse('meal_list')
return HttpResponseRedirect(redirect_url)
else:
form = MealForm(instance=meal)
args = {}
args.update(csrf(request))
args['form'] = form
args['meal'] = meal
return render_to_response(template_name, args)
不限想法?謝謝!