gpt4 book ai didi

python - 无法访问模板中的foreignKey

转载 作者:行者123 更新时间:2023-12-01 00:24:48 25 4
gpt4 key购买 nike

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

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

模型.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()

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

最佳答案

您已为 TaskImages 中的 UserTasks 设置了 lated_name 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

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

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com