我正在尝试访问模板中的foreignKey对象,但它根本不显示任何内容。
我想显示保存在数据库中的ImageField的网址
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 %}
答案 0 :(得分:2)
您在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