Lesnie Sncheider
Lesnie Sncheider

Reputation: 375

Can't access foreignKey in template

I'm trying to access a foreignKey object in my template, but it doesn't show anything at all.

I'd like to show the url to the ImageField saved in the db

Models.py

class Usertasks(models.Model):
    TaskID = models.CharField(max_length=55)
    user = models.ForeignKey(User, unique=False, on_delete=models.CASCADE)
    TaskStatus = models.CharField(max_length=15, default="missing")

class TaskImages(models.Model):
    UserTasks = models.ForeignKey(Usertasks, related_name='images', on_delete=models.CASCADE)
    image = models.ImageField()

views.py

def task_info(request, taskid):
    task = Usertasks.objects.get(TaskID=taskid)
    taskhtml = Usertasks.objects.filter(TaskID=taskid)
    files = os.listdir(task.OutputPath)
    fullpath = task.OutputPath
    print(files)
    for img in files:
        imagepath = fullpath + "/" + img
        task_image = TaskImages()
        task_image.UserTasks = task
        task_image.image = imagepath
        task_image.save()
    return render(request, 'dashboard/task.html', {'query':taskhtml})

html

{% for item in query.image_set.all %}

<img src="{{ item.url }}">

{% endfor %}

Upvotes: 1

Views: 76

Answers (1)

Jason
Jason

Reputation: 11363

You have the related_name kwarg set for UserTasks in TaskImages. Therefore you use that value in place for _set

https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.ForeignKey.related_name

https://docs.djangoproject.com/en/2.2/topics/db/queries/#following-relationships-backward

You can override the FOO_set name by setting the related_name parameter in the ForeignKey definition.

For your issue, you'd need to use query.images, rather than image_set

Upvotes: 2

Related Questions