models.py:
class TestPhoto(models.Model):
file = models.ImageField()
views.py:
def print_test(request):
if request.method == "POST":
if request.is_ajax():
testphoto = TestPhoto.objects.all().last()
# Here is what I'm asking
print({{ testphoto.file.url }})
return JsonResponse({'success': 'printed'})
如何获取views.py上的模板标签呈现的数据:{{ testphoto.file.url }}
我想在views.py中获取模板标签呈现的数据。
答案 0 :(得分:1)
您可以为此使用Template
类:
from django.template import Context, Template
def print_test(request):
if request.method == "POST":
if request.is_ajax():
testphoto = TestPhoto.objects.all().last()
# Here is what I'm asking
template = Template("{{ testphoto.file.url }}")
context = Context({"testphoto": testphoto})
print(template.render(context)) # give you rendered value
return JsonResponse({'success': 'printed'})
UPD
但是,如果您只需要图像的网址,则可以使用简单的方法:
print(testphoto.file.url)