我正在尝试访问模板中的foreignKey对象,但它根本不显示任何内容。

我想显示保存在数据库中的ImageField的网址

型号

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 %}

最佳答案

您已在related_name中为UserTasks设置了TaskImages kwarg。因此,您将该值用于_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


  您可以通过在ForeignKey定义中设置related_name参数来覆盖FOO_set名称。


对于您的问题,您需要使用query.images,而不是image_set

关于python - 无法访问模板中的外键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58673866/

10-11 08:54
查看更多