简体   繁体   中英

Django display in html from views.py

I'm newbie in Django and i would like to have a little help please. I have this code in views.py

def display_meta(request):
    values = request.META.items()
    values.sort
    html = []
    for k, v in values:
        html.append('<tr><td>%s</td><td>%s</td></tr>' % (k, v))
    return HttpResponse('<table>%s</table>' % '/n'.join(html))

------- return render(HttpResponse,'current_datetime.html',{'about': html})

def current_datetime(request):
    now = datetime.datetime.now()
    return render(request, 'current_datetime.html', {'current_date': now})

The part with '------' is added by me but i don't know if it's ok . The question is here , how should I display in the html file the return HttpResponse to show what meta is the user using.

{% extends "base.html" %}

{% block title %}The current time{% endblock %}

{% block content %}
<p>It is now {{ current_date }}.</p>
<p>You are using {{ HERE WILL BE DISPLAYED THE META FUNCTION, BUT HOW ??? }}</p>
{% endblock %}

{% block footer %}
 <hr>
 <p>Thanks for visiting my site.</p>
{% endblock %}

I couldn't understand exactly how to .... Thank you guys in advence!

in settings.py add read what this mean

TEMPLATE_CONTEXT_PROCESSORS = (
    ...,
    'django.core.context_processors.request',

)

and then, it is VERY important to load your custom templatetag

{% extends "base.html" %}

# NEW LINE
{% load  custom_tags %}

{% block title %}The current time{% endblock %}

{% block content %}
    <p>It is now {{ current_date }}.</p>
    <p>You are using {{ request|extract_meta }}</p>
{% endblock %}

{% block footer %}
 <hr>
 <p>Thanks for visiting my site.</p>
{% endblock %}

Create custom template tags named extract_meta here is doc

in templatetags/custom_tags.py:

from django import template

register = template.Library()

@register.filter(name="extract_meta")
def extract_meta(request):
    values = request.META.items()
    values.sort
    html = []
    for k, v in values:
        html.append('<tr><td>%s</td><td>%s</td></tr>' % (k, v))
    return '<table>%s</table>' % '/n'.join(html)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM