'Django - Object list inside object list
I'm using Django to render a list of tube numbers with their attached ingredient. When clicking on a tube number it renders the list of all the ingredients. Then if I click on an ingredient I want it to replace the saved ingredient for this tube. But I don't know how to proceed, if I should do a sub-app for ingredients in my tube app, or if their is a way to keep the tube id.
I tried many things, here is my actual views :
def tube_view(request):
tubes = Tube.objects.all()
return render(request, 'tube_ing.html', {'tubes': tubes})
def tube_detail_view(request, my_id):
obj = get_object_or_404(Tube, id=my_id)
request.session['my_id'] = my_id
ings = Ing.objects.all()
return render(request, "tube_detail.html", {"obj": obj, "ings": ings)
def tube_choice(request, id_ing):
obj = get_object_or_404(Ing, id=id_ing)
request.session['id_ing'] = id_ing
data = {'qty': 100}
form = TubeForm(data)
return render(request, "tube_choice.html", {"obj": obj, 'form': form})
def tube_form(request):
if request.method == 'POST':
form = TubeForm(request.POST)
if form.is_valid():
id_ing = request.session['id_ing']
form.cleaned_data['name_ing'] = my_id
t = Tube(name_ing_tube=name_ing_ing)
t.save()
else:
return HttpResponseRedirect('/tube_ing/')
else:
return HttpResponseRedirect('/tube_ing/')
My models :
class Tube(models.Model):
tube_number = models.IntegerField()
name_ing = models.CharField(null=False, blank=True, max_length=255, default='')
qty = models.IntegerField(default=0)
def get_absolute_url(self):
return reverse('tube_ing:tube_detail', kwargs={"my_id": self.id})
class Ing(models.Model):
name_ing = models.CharField(null=False, blank=True, max_length=255, default='')
def get_absolute_url(self):
return reverse('tube_ing:tube_choice', kwargs={"id_ing": self.id})
And my url patterns :
path('', views.tube_view, name='tube_view'),
path('<int:my_id>/', views.tube_detail_view, name='tube_detail'),
path('ing/<int:id_ing>/', views.tube_choice, name='tube_choice'),
path('ing/tube_form/', views.tube_form, name='tube_form')
So I don't know what to put in my form and how to proceed to keep the tube's info. Thanks a lot to the ones who will take some time to help me on this.
Solution 1:[1]
if [there's] a way to keep the tube id[?]
Yes, in your tube_form function try accessing request.session['my_id'], the tube ID was established from the the tube_detail_view.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Binarydreamer |
