Error during template rendering что делать

Извините, если это нубский код или вопрос. Я делаю нумерацию страниц с использованием django-pagination, и я делаю это так. Но это дает мне keyError на моей странице, кроме того, он упоминает, что это ошибка во время рендеринга шаблона. Что я делаю не так здесь. Я успешно установил нумерацию страниц....

Извините, если это нубский код или вопрос. Я делаю нумерацию страниц с использованием django-pagination, и я делаю это так. Но это дает мне keyError на моей странице, кроме того, он упоминает, что это ошибка во время рендеринга шаблона. Что я делаю не так здесь. Я успешно установил нумерацию страниц, изменил файл settings.py. Но я не знаю, что мне нужно делать здесь. Любая помощь будет высоко оценен.

 <table class="active_table"  summary="active_user">
    <thead>
     <tr><th>Name</th><th>Mobile Number</th><th>Count</th></tr>
    </thead>
    <tbody id="table_content">
     {% load pagination_tags %}
       {% block content %}
         {% autopaginate response_data 5 %}
           {% for b in response_data %}
              <tr class="table_rows"><td>{{ b.name }}</td><td>{{ b.mobile_number }}</td><td>{{ b.count }}</td></tr>
           {% endfor %}
         {% paginate %}
        {% endblock %}
     </tbody>
  </table>

Подробная информация о трассировке вставлена здесь http://dpaste.com/919526/

Код вида следующий

Views.py

@csrf_exempt

Def active_user_table (request, b): if request.method! = «GET»: поднять Http404

if (b=='4'):
         cursor = connection.cursor()
         cursor.execute("SELECT core_user.id, name,mobile_number,COUNT(*) as count, created FROM core_user,core_useractivity WHERE core_user.id = core_useractivity.user_id GROUP BY user_id ORDER BY count DESC")
         response_data = dictfetchall(cursor)
         return render_to_response("siteadmin/active_user_table.tmpl",{'response_data':response_data})
elif (b=='3'):
         cursor = connection.cursor()
         cursor.execute("SELECT core_user.id, name, mobile_number, COUNT(*) as count, created FROM core_user, core_useractivity WHERE core_user.id = core_useractivity.user_id AND MONTH(CAST(created as date)) = MONTH(NOW()) AND YEAR(cast(created as date)) = YEAR(NOW()) GROUP BY user_id ORDER BY count DESC")
         response_data = dictfetchall(cursor)
         return render_to_response("siteadmin/active_user_table.tmpl",{'response_data': response_data})
elif (b=='2'):
         cursor = connection.cursor()
         cursor.execute("SELECT core_user.id, name, mobile_number, COUNT(*) as count, created FROM core_user, core_useractivity WHERE core_user.id = core_useractivity.user_id AND DATEDIFF(NOW(), created) <= 7 GROUP BY user_id ORDER BY count DESC")
         response_data = dictfetchall(cursor)
         return render_to_response("siteadmin/active_user_table.tmpl",{'response_data': response_data})
elif (b=='1'):
         cursor = connection.cursor()
         cursor.execute("SELECT core_user.id, name, mobile_number, COUNT(*) as count, created FROM core_user, core_useractivity WHERE core_user.id = core_useractivity.user_id AND DATE(created) = DATE(NOW())")
         response_data = dictfetchall(cursor)
         return render_to_response("siteadmin/active_user_table.tmpl",{'response_data': response_data})
else:
         raise Http404

Извините, я не использую django ORM на данный момент, но я сделаю это в будущем.

4 ответа

Лучший ответ

Я решил это сам, но благодаря ndpu за помощь по крайней мере, я убедился, что не было никакой другой проблемы, кроме некоторых проблем с настройками. В этом вопросе у меня проблемы с настройкой django-pagination. Alasdair упомянул добавление «django.contrib.auth.context_processors.auth» в TEMPLATE_CONTEXT_PROCESSORS. Просто добавив его, я получаю правильные ожидаемые значения.


4

Community
23 Май 2017 в 12:31

Для тех, кто использует ярлык рендеринга и все еще сталкиваясь с этой ошибкой, просто добавьте {'request':request} в переменную контекста

context = { ..., 'request':request}
return render(request, 'templatename.html', context)


1

srj
25 Фев 2015 в 12:55

Вы должны добавить context_instance в вызове render_to_response:

return render_to_response("siteadmin/active_user_table.tmpl",{'response_data': response_data}, context_instance=RequestContext(request))

Или вы можете использовать кортеж TEMPLATE_CONTEXT_PROCESSORS в файле settings.py. Добавьте эту строку «django.core.context_processors.request» к процессорам контекста, и каждый RequestContext будет содержать запрос переменной.


4

ndpu
11 Фев 2013 в 10:10

Я тоже сталкиваюсь с этой ошибкой ранее. Я получил следующую ошибку: Внутренняя ошибка сервера: / cancel-email /

Internal Server Error: /cancel-email/
Traceback (most recent call last):
  File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/base.py", line 506, in parse
    compile_func = self.tags[command]
KeyError: 'static'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/kashif/recEnv/lib/python3.6/site-packages/django/core/handlers/base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/kashif/recEnv/lib/python3.6/site-packages/django/core/handlers/base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/kashif/recEnv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/var/www/recruiter-new/recruiter/scheduler.py", line 803, in cancelEmail
    return render(request,'scheduler/cancel-email-part.html',{"cancel_email" :EmailDetail})
  File "/home/kashif/recEnv/lib/python3.6/site-packages/django/shortcuts.py", line 67, in render
    template_name, context, request=request, using=using)
  File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/loader.py", line 96, in render_to_string
    template = get_template(template_name, using=using)
  File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/loader.py", line 32, in get_template
    return engine.get_template(template_name, dirs)
  File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/backends/django.py", line 40, in get_template
    return Template(self.engine.get_template(template_name, dirs), self)
  File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/engine.py", line 190, in get_template
    template, origin = self.find_template(template_name, dirs)
  File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/engine.py", line 157, in find_template
    name, template_dirs=dirs, skip=skip,
  File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/loaders/base.py", line 46, in get_template
    contents, origin, origin.template_name, self.engine,
  File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/base.py", line 189, in __init__
    self.nodelist = self.compile_nodelist()
  File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/base.py", line 230, in compile_nodelist
    return parser.parse()
  File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/base.py", line 508, in parse
    self.invalid_block_tag(token, command, parse_until)
  File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/base.py", line 568, in invalid_block_tag
    "or load this tag?" % (token.lineno, command)
django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 74: 'static'. Did you forget to register or load this tag?
[07/Aug/2018 08:43:26] "POST /cancel-email/ HTTP/1.1" 500 20789

Я попробовал некоторые решения Google, но не смог решить, затем, наконец, снова проверил мой код и обнаружил глупую ошибку в файле шаблона.

Просто добавь:

{% load static %}

Поверх вашего файла шаблона.


0

Kashif Anwar
7 Авг 2018 в 09:00

Содержание

  1. Error during template rendering django
  2. ключевая ошибка в Django. Во время рендеринга шаблона
  3. Views.py
  4. 4 ответа

Error during template rendering django

Don’t understand the point where i’m missing.

In urls.py, is that path() in the urlpatterns assignment?
‘’’

Are there any other patterns in urls.py?

yes it is in urlpatterns.

May be you can get something from Traceback Message:

Is urls.py the one in the project folder, or is it in /blogs? If it’s in the app, can we please see your root urls.py?

it’s the blog app folder not the root folder.
root folder code is:

It seems that you’re including the blog/urls.py in the project with a namespace. In that case, the reverse would be namespace:view name, or in your case, blog:login. Try that in your template inside the url tag and see if that works.

Ok so got that fixed thanks a lot. just a newbie problem. but the learning was good. i forgot about the namespace.

The first time I had that happen, it took me HOURS to figure it out. Glad I could help!

can you please send a screenshot of your fixed code? im having the same issue

Can you put your template code here. Main problem is there only. The reverse would be namespace:view in template rendering.

Thank you! This is the answer I was looking for aswell,

I was searching for this!! you’ve solved my issue!! thank you so much!!

this is my project urls.py

and here is the blog app urls.py

i’m still getting this error…
Reverse for ‘blog-home’ not found. ‘blog-home’ is not a valid view function or pattern name.
Any kind of help will be highly appreciated.

In the project urls.py, you have this:

(snipped the remainder for brevity’s sake)

The namespace is added to the front of the reverse. I don’t know if one is allowed to have a colon in the namespace, as I’ve never tried that. I would write this as so:

Which makes the reverse for the ‘’ path as blog:blog-home. What does your template where this error comes up look like?

This is the correct answer. I thought it was optional to add the namespacing to a url tag especially because I had only one application. Thanks

the same mistake question,info is…

|Request URL:|http://127.0.0.1:8000/store/cart/|
|Django Version:|2.1.8|
|Exception Type:|NoReverseMatch|
|Exception Value:|Reverse for ‘store’ not found. ‘store’ is not a valid view function or pattern name.|

django.urls.exceptions.NoReverseMatch: Reverse for ‘store’ not found. ‘store’ is not a valid view function or pattern name.
[09/Dec/2020 12:54:04] “GET /store/cart/ HTTP/1.1” 500 157901

django-admin startproject [projectname]
. setting>urls.py
urlpatterns = [
path(‘store/’, include(‘store.urls’, namespace=‘store’)),
path(‘posts/’, include(‘posts.urls’, namespace=‘posts’)),
path(’’, include(‘home.urls’)),
path(‘admin/’, admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

python manage.py startapp store
. store/url.py

urlpatterns = [
path(‘store/’, views.store, name=‘store’),
path(‘cart/’, views.cart, name=‘cart’),
path(‘checkout/’, views.checkout, name=‘checkout’),
]

def cart(request):
data = cartData(request)

Can someone help? What should I do?
Or … Or what information should I give less? PLZ…

Somewhere in a view or template you’re attempting to reverse a url named ‘store’. You can try ‘store:store’. If that doesn’t work, we’ll need to see the view or template that is generating this error.

return render(request, ‘store/store.html’, context)

you say mean is —> return render(request, <>, context).
or —> return render(request, “store:store”, context).

I have tried both of these methods, but this problem will evolve in the future, but there are no errors in my program, and running out of the dict makes me a little puzzled QWQ

Attach the link to the result after the operation: https://paste.ubuntu.com/p/TJKWBBwSTc/

How to write
return render(request,‘store/cart.html’, context) .

1.return render(request,‘store: store’, context)
or
2.return render(request, <>, context)
I have tried both of these methods, but this problem will evolve in the future, but there are no errors in my program, and running out of the dict makes me a little puzzled QWQ

Attach follow-up results:

sorry for bothering,

  1. Add app_name =‘store’ in urls.py ->

Then in my views.py,
def store(request):
data = cartData(request)

—-> return render(request, <>, context)
—-> return render(request, <>, context)
—-> return render(request, <>, context)

<> After this is used,
This message is produced Exception Value: unhashable type:‘dict’

Excuse me, is this <> wrong? Someone uses something like this? Or there are keywords that allow me to query django. I really don’t see these things in the django data. QWQ also rarely sees people using this way. Can they give me similar knowledge? ?

  1. If I “do not” do this <><><>, enter the shopping cart http://127.0.0.1:8000/store/cart/ will produce This error occurred: Reverse for’store’‘cart’‘checkout’ not found.‘store’ is not a valid view function or pattern name.

Then very unexpectedly, there is no error in def store, def cart(request):, the problem is the dict in the cart

Picture two and three are the same,
Is it a symbol problem in the () [] <> def cart() program?
def cart(request):
data = cartData(request)

<> -> It is impossible to change django to [[ ]] (()) like this R… strange QWQ

Thank you in advance

CAN visit views.pt.py

from django.shortcuts import render
from django.http import JsonResponse
import json
import datetime
from .models import *
from .utils import cookieCart, cartData, guestOrder

def store(request):
data = cartData(request)

def cart(request):
data = cartData(request)

def checkout(request):
data = cartData(request) # The amount of cookiesData is changed to data change -> cookieData = cookieCart(request)
cartItems = data[‘cartItems’] # cartItems = cookieData[‘cartItems’]
order = data[‘order’] # order = cookieData[‘order’]
items = data[‘items’] # items = cookieData[‘items’]

Источник

ключевая ошибка в Django. Во время рендеринга шаблона

Извините, если это нубский код или вопрос. Я делаю нумерацию страниц с использованием django-pagination, и я делаю это так. Но это дает мне keyError на моей странице, кроме того, он упоминает, что это ошибка во время рендеринга шаблона. Что я делаю не так здесь. Я успешно установил нумерацию страниц, изменил файл settings.py. Но я не знаю, что мне нужно делать здесь. Любая помощь будет высоко оценен.

Подробная информация о трассировке вставлена здесь http://dpaste.com/919526/

Код вида следующий

Views.py

Def active_user_table (request, b): if request.method! = «GET»: поднять Http404

Извините, я не использую django ORM на данный момент, но я сделаю это в будущем.

4 ответа

Я решил это сам, но благодаря ndpu за помощь по крайней мере, я убедился, что не было никакой другой проблемы, кроме некоторых проблем с настройками. В этом вопросе у меня проблемы с настройкой django-pagination. Alasdair упомянул добавление «django.contrib.auth.context_processors.auth» в TEMPLATE_CONTEXT_PROCESSORS. Просто добавив его, я получаю правильные ожидаемые значения.

Для тех, кто использует ярлык рендеринга и все еще сталкиваясь с этой ошибкой, просто добавьте <‘request’:request>в переменную контекста

Вы должны добавить context_instance в вызове render_to_response:

Или вы можете использовать кортеж TEMPLATE_CONTEXT_PROCESSORS в файле settings.py. Добавьте эту строку «django.core.context_processors.request» к процессорам контекста, и каждый RequestContext будет содержать запрос переменной.

Я тоже сталкиваюсь с этой ошибкой ранее. Я получил следующую ошибку: Внутренняя ошибка сервера: / cancel-email /

Я попробовал некоторые решения Google, но не смог решить, затем, наконец, снова проверил мой код и обнаружил глупую ошибку в файле шаблона.

Источник

t_forward

0 / 0 / 0

Регистрация: 24.02.2021

Сообщений: 51

1

18.07.2021, 21:17. Показов 4203. Ответов 6

Метки django, django 3 (Все метки)


Пишу сайт на Django по книги Дронова. Использую Django 3.0. И в главе 2.7 «Наследование шаблонов» вылезает ошибка: Error during template rendering

In template C:PythonDjango 3samplesitebboardtemplateslayoutbasic.html, error at line 0
Reverse for ‘by_rubric’ with arguments ‘(»,)’ not found. 1 pattern(s) tried: [‘bboard/(?P<rubric_id>[0-9]+)/$’]
что делать, и как может быть ошибка в строке 0?
Basic.html:

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>{% block title %}Главная{% endblock %} :: Доска объявлений</title>
</head>
<body>
<header>
    <h1>Объявления</h1>
</header>
    <nav>
         <a href="{% url 'index' %}">Главная</a>
        <a href="{% url 'add' %}">Добавить</a>
        {% for rubric in rubrics %}
        <a href="{% url 'by_rubric' rubric.pk %}">{{ rubric.name }}</a>
        {% endfor %}
    </nav>
<section>
  {% block content %}
  {% endblock %}
  {% block paginator %}
  {% endblock %}
</section>
</body>
</html>

index.html:

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{% extends "layout/basic.html" %}
{% block content %}
    {% for bb in bbs %}
    <div>
        <h2>{{ bb.title }}</h2>
        <p>{{ bb.content }}</p>
        <p><a href="{% url 'by_rubric' bb.rubric.pk %}">{{ bb.rubric.name }}</a></p>
        <p>{{ bb.published|date:"d.m.Y H:i:s" }}</p>
    </div>
    {% endfor %}
{% endblock %}
{% block paginator %}
        {% if page.has_previous %}
        <a href="?page={{ page.previous_page_number }}">&lt;</a>
        &nbsp;&nbsp;|&nbsp;&nbsp;
        {% endif %}
        Часть №{{ page.number }} из {{ page.paginator.num_pages }}
        {% if page.has_next %}
        &nbsp;&nbsp;|&nbsp;&nbsp;
        <a href="?page={{ page.next_page_number }}">&gt;</a>
        {% endif %}
{% endblock %}

Ошибка вылезает при переходе на страницу http://127.0.0.3:8000/bboard/?page=2. Там применяется пагинация.

Error during template rendering  In template C:PythonDjango 3samplesitebboardtemplateslayoutbasic.html, error at

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



21 / 12 / 9

Регистрация: 12.02.2020

Сообщений: 126

18.07.2021, 23:12

2

Специально скачал книгу и посмотрел главу 2.7… И ты знаешь, что-то не нашел я там пагинацию…
Пришли функцию с пагинацией



1



t_forward

0 / 0 / 0

Регистрация: 24.02.2021

Сообщений: 51

19.07.2021, 09:38

 [ТС]

3

Roman020 пагинацию я сам делал, но тоже по книги.

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
from django.shortcuts import render
from django.core.paginator import Paginator
from django.views.generic.edit import CreateView
from django.urls import reverse_lazy
 
from .models import Bb
from .models import Rubric
from .forms import BbForm
 
class BbCreateView(CreateView):
    template_name = 'bboard/create.html'
    form_class = BbForm
    success_url = reverse_lazy('index')
 
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['rubrics'] = Rubric.objects.all()
        return context
 
def index(request):
    bbs = Bb.objects.all()
    rubrics = Rubric.objects.all()
    paginator = Paginator(bbs,5)
    if 'page' in request.GET:
        page_num = request.GET['page']
    else:
        page_num = 1
    page = paginator.get_page(page_num)
    context = {'bbs': bbs, 'rubrics': rubrics,'page': page, 'bbs':page.object_list}
    return render(request,'bboard/index.html',context)
def by_rubric(request,rubric_id):
    bbs = Bb.objects.filter(rubric = rubric_id)
    rubrics = Rubric.objects.all()
    current_rubric = Rubric.objects.get(pk=rubric_id)
    paginator = Paginator(bbs, 5)
    if 'page' in request.GET:
        page_num = request.GET['page']
    else:
        page_num = 1
    page = paginator.get_page(page_num)
    context = {'bbs': bbs, 'rubrics': rubrics, 'page': page, 'bbs': page.object_list,'current_rubric':current_rubric}
    return render(request,'bboard/by_rubric.html',context)

index.html:

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{% extends "layout/basic.html" %}
{% block content %}
    {% for bb in bbs %}
    <div>
        <h2>{{ bb.title }}</h2>
        <p>{{ bb.content }}</p>
        <p><a href="{% url 'by_rubric' bb.rubric.pk %}">{{ bb.rubric.name }}</a></p>
        <p>{{ bb.published|date:"d.m.Y H:i:s" }}</p>
    </div>
    {% endfor %}
{% endblock %}
{% block paginator %}
        {% if page.has_previous %}
        <a href="?page={{ page.previous_page_number }}">&lt;</a>
        &nbsp;&nbsp;|&nbsp;&nbsp;
        {% endif %}
        Часть №{{ page.number }} из {{ page.paginator.num_pages }}
        {% if page.has_next %}
        &nbsp;&nbsp;|&nbsp;&nbsp;
        <a href="?page={{ page.next_page_number }}">&gt;</a>
        {% endif %}
{% endblock %}



0



0 / 0 / 0

Регистрация: 24.02.2021

Сообщений: 51

19.07.2021, 21:24

 [ТС]

5

Roman020 я убрал пагинацию, но всё тоже самое



0



21 / 12 / 9

Регистрация: 12.02.2020

Сообщений: 126

19.07.2021, 21:48

6

Откуда у тебя взялась ссылка вида ?page=2?
У тебя же прописан путь [‘bboard/(?P<rubric_id>[0-9]+)/$’], и соответственно в функции def by_rubric(request,rubric_id): указан id рубрики.

У тебя ссылка должна быть вида: http://127.0.0.3:8000/bboard/2/. Где вместо 2 свой id рубрики



0



SerB85

0 / 0 / 0

Регистрация: 19.07.2022

Сообщений: 1

19.07.2022, 22:50

7

Я нашел опечатку в книге.
Нужно писать

Python
1
{% extends "./layout/basic.html" %}



0



Понравилась статья? Поделить с друзьями:
  • Error during ssl handshake with remote server returned by
  • Error during sonarqube scanner execution
  • Error during simulation turbulence fd
  • Error during session construction перевести
  • Error during servletcontainerinitializer processing