uum i have a Db model like this (code below) and i went to get the all the courses that are associated to a user i user field and print out their title NOTE i have an already existing course model and user model
‘’’
class StudentCourses(models.Model):
course = models.ForeignKey(Course, on_delete = models.DO_NOTHING)
user = models.ForeignKey(User, on_delete = models.DO_NOTHING)
date_purchased = models.DateField(auto_now_add=True)
class Meta:
db_table = 'student_courses'
verbose_name_plural = 'student courses'
unique_together = ('course', 'user')
def __str__(self):
return self.course.title + " owned by " + self.user.first_name
‘’’
i was able to do this
‘’’
def courses_me(request):
user = request.user
try:
courses = StudentCourses.objects.filter(user_id=user.id)
print( courses)
except StudentCourses.DoesNotExist:
courses = None
return render(request, “dashboard/student/student-my-courses.html”, {‘courses’:courses})
‘’’
but i could not print out the course title from it.
We’ll need to see the Course object. We’ll likely also need to see the student-my-courses
template as well.
Also, since this is effectively a “through” table in the middle of a ManyToMany relationship between Course and User, it doesn’t make any sense to have “on_delete=DO_NOTHING”. (In fact, it’s potentially dangerous.) For this type of table, it really should be CASCADE.
Since you’ve got potentially-incorrect or invalid data in your database, you probably want to verify that those foreign keys are valid.
Finally, when you’re posting code, make sure it’s enclosed between lines of three backtick - ` characters, not single-quotes - '.
thanks ken here is the StudentCourse model
class StudentCourses(models.Model):
course = models.ForeignKey(Course, on_delete = models.DO_NOTHING)
user = models.ForeignKey(User, on_delete = models.DO_NOTHING)
date_purchased = models.DateField(auto_now_add=True)
class Meta:
db_table = 'student_courses'
verbose_name_plural = 'student courses'
unique_together = ('course', 'user')
def __str__(self):
return self.course.title + " owned by " + self.user.first_name
here is the html template
{% if courses %}
<div class="card-columns">
{% for course in courses %}
<div class="card">
<div class="card-header">
<div class="media">
<div class="media-left">
<a href="student-student-take-course.html">
<img src="/media/{{ course.photo }}"
alt="Card image cap"
width="100"
class="rounded">
</a>
</div>
<div class="media-body">
<h4 class="card-title m-0"><a href="student-take-course.html">{{course.user.email }}</a></h4>
<small class="text-muted">Lessons: 3 of 7</small>
</div>
</div>
</div>
<div class="progress rounded-0">
<div class="progress-bar progress-bar-striped bg-primary"
role="progressbar"
style="width: 40%"
aria-valuenow="40"
aria-valuemin="0"
aria-valuemax="100"></div>
</div>
<div class="card-footer bg-white">
<a href="student-take-course.html"
class="btn btn-primary btn-sm">Continue <i class="material-icons btn__icon--right">play_circle_outline</i></a>
</div>
</div>
{% endfor %}
</div>
{% endif %}
here is my course model
class Course(models.Model):
course_id = models.CharField(max_length=50, editable=False)
title = models.CharField(max_length=350)
slug = models.SlugField(max_length=100)
category = models.ForeignKey(Category, on_delete = models.CASCADE)
description = RichTextField()
objective = RichTextField()
eligibility = RichTextField()
instructor = models.ForeignKey(User, on_delete = models.CASCADE)
photo = models.ImageField(null=True, upload_to='courses/photos/')
price = models.DecimalField(decimal_places=2, max_digits=10)
created_on = models.DateField(editable=False, auto_now_add=True)
last_modified = models.DateField(editable=False, auto_now=True)
def save(self, *args, **kwargs):
self.course_id = "CC" + str(random.randint(1000000, 90000000))
value = self.title
self.slug = slugify(value, allow_unicode=True)
super(Course, self).save(*args, **kwargs)
class Meta:
db_table = 'courses'
def __str__(self):
return self.title
here is my views
def courses_me(request):
user = request.user
try:
courses = StudentCourses.objects.filter(user_id=user.id)
print( courses)
except StudentCourses.DoesNotExist:
courses = None
return render(request, "dashboard/student/student-my-courses.html", {'courses':courses})
what i want to achieve is this: to print out the courses (and their attributes) that are associate to the user in the StudentCourse model. Note the student course model is a model that holds the courses subscribed to buy a student
I see the loop where you’re iterating through the individual StudentCourse objects (for course in courses
) but then I don’t see where you’re trying to use that reference within the template to get the titles.
Note, one item that is a potential source of confusion is that you’re not passing Course
objects into your template. Your context contains StudentCourse objects, but you’ve named the variable courses
. In your template then, the reference to the Course
object would be course.course.<field>
. I would suggest you rename your context variable to make it clear you’re working with StudentCourses
and not Course
.
thanks ken it works error was from naming and passing the context as you mentioned. Here is what i now did… Views
def courses_me(request):
user = request.user
try:
studentcourses = StudentCourses.objects.filter(user_id=user.id)
except StudentCourses.DoesNotExist:
studentcourses = None
return render(request, "dashboard/student/student-my-courses.html", {'studentcourses':studentcourses})
…template
{% if studentcourses %}
<div class="card-columns">
{% for course in studentcourses %}
<div class="card">
<div class="card-header">
<div class="media">
<div class="media-left">
<a href="student-student-take-course.html">
<img src="/media/{{ course.course.photo }}"
alt="Card image cap"
width="100"
class="rounded">
</a>
</div>
<div class="media-body">
<h4 class="card-title m-0"><a href="student-take-course.html">{{ course.course.title }}</a></h4>
<small class="text-muted">Lessons: 3 of 7</small>
</div>
</div>
</div>
<div class="progress rounded-0">
<div class="progress-bar progress-bar-striped bg-primary"
role="progressbar"
style="width: 40%"
aria-valuenow="40"
aria-valuemin="0"
aria-valuemax="100"></div>
</div>
<div class="card-footer bg-white">
<a href="student-take-course.html"
class="btn btn-primary btn-sm">Continue <i class="material-icons btn__icon--right">play_circle_outline</i></a>
</div>
</div>
{% endfor %}
</div>
{% endif %}
thanks again