Home > Back-end >  Adding Context to Class Based View Django Project
Adding Context to Class Based View Django Project

Time:08-29

I have a problem with showing a queryset of a specific model in my Gym project. I have tried many different query's but none is working

the models:

class Workout(models.Model):
    name = models.CharField(max_length = 30,blank=True, null=True)

class Exercise(models.Model):
    workout = models.ForeignKey(Workout, on_delete=models.CASCADE, related_name='exercises',blank=True, null=True)
    name = models.CharField(max_length = 30, blank=True, null=True)

class Breakdown(models.Model):
    exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, related_name='excercise',blank=True, null=True)
    repetitions = models.IntegerField()

I am trying to showing the repetitions in the Breakdown model which has a ForeignKey relation with Exercise which has a ForeignKey relation with Workout

views.py

class home(ListView):
    model = Workout
    template_name = 'my_gym/home.html'
    context_object_name = 'workouts'

class workout_details(ListView):
    model = Exercise
    template_name = 'my_gym/start_workout.html'
    context_object_name = 'exercises'
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['breakdown'] = Exercise.objects.filter(breakdown=self.breakdown)
        return context

urls.py

urlpatterns = [
    path('', home.as_view(), name='home'),
    path('workout/<int:pk>/', workout_details.as_view(), name='workout'),
]

template:

{% for e in exercises %}
{{ e.name }}
{{ breakdown.repetitions }}
{% endfor %}

My question what is my mistake here that is either getting me an error or not showing the required data set. my objective is the choose from the home page a Workout from list and next page to be the list of exercises with the repitions related to it.

CodePudding user response:

get_context_data() is a method calculated for view, not a loop to use inside a template or something similar. You have set nice relations, use them properly.

Firstfully, change related_name here to something that will not be confusing:

class Breakdown(models.Model):
    exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, related_name='breakdowns', blank=True, null=True)

With that done, delete whole get_context_data() and change template to:

{% for e in exercises %}
    {{ e.name }}
    {% for b in e.breakdowns.all %}
        {{ b.repetitions }}
    {% endfor %}
{% endfor %}
  • Related