Most of the questions on this seem to be focused on saving down m2m tables. I'm curious about how to view fields from the intermediary table in one (or two combined) forms.
The idea is I have many resources and many meals. Different meals can have the same resource, but in differing amounts. Say: Burrito has x lbs of beef, but fajitas have y.
I want to create a form to edit the Burrito meal so that I can see/edit/create: The name of the meal, the resources in the meal, and the amount associated with the resource in that meal. My current code displays a form with all but the amounts associated with the resources via the m2m table
I have two models connected through an intermediary table:
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)
I'm trying to use a simple ModelForm as seen below:
class MealForm(forms.ModelForm):
class Meta:
model = Meal
fields = '__all__'
with this view:
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)
Any Ideas? Thank you!