Error during template rendering django

«Error during template rendering» in Django I have 4 model classes (Course, Semester, Subject, TuModelQuestions) as you can see below. When I try to render particular question from TuModelQuestions from Particular Subject From Particular Semester And particular Course. How do I render it? (Overall: I want to render that question only for particular subject, […]

Содержание

  1. «Error during template rendering» in Django
  2. 1 Answer 1
  3. django application getting error during template rendering
  4. Create your views here.
  5. 2 Answers 2
  6. Documentation
  7. Templates¶
  8. Support for template engines¶
  9. Configuration¶
  10. Usage¶
  11. Built-in backends¶
  12. Custom backends¶
  13. Debug integration for custom engines¶
  14. Template postmortem¶
  15. Contextual line information¶
  16. Origin API and 3rd-party integration¶
  17. The Django template language¶
  18. Syntax¶
  19. Variables¶
  20. Filters¶

«Error during template rendering» in Django

I have 4 model classes (Course, Semester, Subject, TuModelQuestions) as you can see below. When I try to render particular question from TuModelQuestions from Particular Subject From Particular Semester And particular Course. How do I render it?

(Overall: I want to render that question only for particular subject, course and semester).

models.py

views.py

model-questions.html

urls.py

What I want is in this picture:

1 Answer 1

In the example you provided, it seems like you’re passing two keys in your context dictionary, these being obj and model_question . The problem is, you’re not displaying them anywhere in your model-questions.html page. Your view seems okay, but your template is where the problem is.

In order to output the data you passed using context , try using the Django template syntax and output these two values.

Wherever you wish to, in your HTML template, add something like this:

If you only want to see a particular field of these objects, you could try something like:

(. ) given the fact that you have a field called faculty in your Subject model.

Источник

django application getting error during template rendering

This is my directory structure of the project

where blog is is the application directory and mysite is te project directory

This is my blog/urls.py

this is blogs/static/post_list.py

this is the views.py

from django.shortcuts import render,get_object_or_404 from .models import Post

Create your views here.

Here is the details of the errors below

2 Answers 2

You should give objects names that refer to what they actually are. For some reason, you are using the name post in the context to refer to the set of posts; when you iterate through that set in the template you call each one posts . This, not surprisingly, confuses you so that when you reference the post’s PK in the URL tag you mistakenly reference post.pk rather than posts.pk .

Name your objects correctly and this won’t happen:

Looks like you’ve not configured the URL dispatcher to include the urls in the blogs/urls.py file. Note that the main urls.py file is the one in the proyect directory. If you want to add another one in an app directory, you must do it explicitly.

Here you can see the documentation on how to do that. Basically, you must add something like this in your mysite/urls.py :

Now you can access that urls, with the prefix blog/ . For example, blog/post/whatever

Источник

Documentation

Templates¶

Being a web framework, Django needs a convenient way to generate HTML dynamically. The most common approach relies on templates. A template contains the static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted. For a hands-on example of creating HTML pages with templates, see Tutorial 3 .

A Django project can be configured with one or several template engines (or even zero if you don’t use templates). Django ships built-in backends for its own template system, creatively called the Django template language (DTL), and for the popular alternative Jinja2. Backends for other template languages may be available from third-parties.

Django defines a standard API for loading and rendering templates regardless of the backend. Loading consists of finding the template for a given identifier and preprocessing it, usually compiling it to an in-memory representation. Rendering means interpolating the template with context data and returning the resulting string.

The Django template language is Django’s own template system. Until Django 1.8 it was the only built-in option available. It’s a good template library even though it’s fairly opinionated and sports a few idiosyncrasies. If you don’t have a pressing reason to choose another backend, you should use the DTL, especially if you’re writing a pluggable application and you intend to distribute templates. Django’s contrib apps that include templates, like django.contrib.admin , use the DTL.

For historical reasons, both the generic support for template engines and the implementation of the Django template language live in the django.template namespace.

The template system isn’t safe against untrusted template authors. For example, a site shouldn’t allow its users to provide their own templates, since template authors can do things like perform XSS attacks and access properties of template variables that may contain sensitive information.

Support for template engines¶

Configuration¶

Templates engines are configured with the TEMPLATES setting. It’s a list of configurations, one for each engine. The default value is empty. The settings.py generated by the startproject command defines a more useful value:

BACKEND is a dotted Python path to a template engine class implementing Django’s template backend API. The built-in backends are django.template.backends.django.DjangoTemplates and django.template.backends.jinja2.Jinja2 .

Since most engines load templates from files, the top-level configuration for each engine contains two common settings:

  • DIRS defines a list of directories where the engine should look for template source files, in search order.
  • APP_DIRS tells whether the engine should look for templates inside installed applications. Each backend defines a conventional name for the subdirectory inside applications where its templates should be stored.

While uncommon, it’s possible to configure several instances of the same backend with different options. In that case you should define a unique NAME for each engine.

OPTIONS contains backend-specific settings.

Usage¶

The django.template.loader module defines two functions to load templates.

get_template (template_name, using=None

This function loads the template with the given name and returns a Template object.

The exact type of the return value depends on the backend that loaded the template. Each backend has its own Template class.

get_template() tries each template engine in order until one succeeds. If the template cannot be found, it raises TemplateDoesNotExist . If the template is found but contains invalid syntax, it raises TemplateSyntaxError .

How templates are searched and loaded depends on each engine’s backend and configuration.

If you want to restrict the search to a particular template engine, pass the engine’s NAME in the using argument.

select_template (template_name_list, using=None

select_template() is just like get_template() , except it takes a list of template names. It tries each name in order and returns the first template that exists.

If loading a template fails, the following two exceptions, defined in django.template , may be raised:

exception TemplateDoesNotExist (msg, tried=None, backend=None, chain=None

This exception is raised when a template cannot be found. It accepts the following optional arguments for populating the template postmortem on the debug page:

backend The template backend instance from which the exception originated. tried A list of sources that were tried when finding the template. This is formatted as a list of tuples containing (origin, status) , where origin is an origin-like object and status is a string with the reason the template wasn’t found. chain A list of intermediate TemplateDoesNotExist exceptions raised when trying to load a template. This is used by functions, such as get_template() , that try to load a given template from multiple engines. exception TemplateSyntaxError (msg

This exception is raised when a template was found but contains errors.

Template objects returned by get_template() and select_template() must provide a render() method with the following signature:

Template. render (context=None, request=None

Renders this template with a given context.

If context is provided, it must be a dict . If it isn’t provided, the engine will render the template with an empty context.

If request is provided, it must be an HttpRequest . Then the engine must make it, as well as the CSRF token, available in the template. How this is achieved is up to each backend.

Here’s an example of the search algorithm. For this example the TEMPLATES setting is:

If you call get_template(‘story_detail.html’) , here are the files Django will look for, in order:

  • /home/html/example.com/story_detail.html ( ‘django’ engine)
  • /home/html/default/story_detail.html ( ‘django’ engine)
  • /home/html/jinja2/story_detail.html ( ‘jinja2’ engine)

If you call select_template([‘story_253_detail.html’, ‘story_detail.html’]) , here’s what Django will look for:

  • /home/html/example.com/story_253_detail.html ( ‘django’ engine)
  • /home/html/default/story_253_detail.html ( ‘django’ engine)
  • /home/html/jinja2/story_253_detail.html ( ‘jinja2’ engine)
  • /home/html/example.com/story_detail.html ( ‘django’ engine)
  • /home/html/default/story_detail.html ( ‘django’ engine)
  • /home/html/jinja2/story_detail.html ( ‘jinja2’ engine)

When Django finds a template that exists, it stops looking.

You can use select_template() for flexible template loading. For example, if you’ve written a news story and want some stories to have custom templates, use something like select_template([‘story_%s_detail.html’ % story.id, ‘story_detail.html’]) . That’ll allow you to use a custom template for an individual story, with a fallback template for stories that don’t have custom templates.

It’s possible – and preferable – to organize templates in subdirectories inside each directory containing templates. The convention is to make a subdirectory for each Django app, with subdirectories within those subdirectories as needed.

Do this for your own sanity. Storing all templates in the root level of a single directory gets messy.

To load a template that’s within a subdirectory, use a slash, like so:

Using the same TEMPLATES option as above, this will attempt to load the following templates:

  • /home/html/example.com/news/story_detail.html ( ‘django’ engine)
  • /home/html/default/news/story_detail.html ( ‘django’ engine)
  • /home/html/jinja2/news/story_detail.html ( ‘jinja2’ engine)

In addition, to cut down on the repetitive nature of loading and rendering templates, Django provides a shortcut function which automates the process.

render_to_string (template_name, context=None, request=None, using=None

render_to_string() loads a template like get_template() and calls its render() method immediately. It takes the following arguments.

template_name The name of the template to load and render. If it’s a list of template names, Django uses select_template() instead of get_template() to find the template. context A dict to be used as the template’s context for rendering. request An optional HttpRequest that will be available during the template’s rendering process. using An optional template engine NAME . The search for the template will be restricted to that engine.

See also the render() shortcut which calls render_to_string() and feeds the result into an HttpResponse suitable for returning from a view.

Finally, you can use configured engines directly:

Template engines are available in django.template.engines :

The lookup key — ‘django’ in this example — is the engine’s NAME .

Built-in backends¶

Set BACKEND to ‘django.template.backends.django.DjangoTemplates’ to configure a Django template engine.

When APP_DIRS is True , DjangoTemplates engines look for templates in the templates subdirectory of installed applications. This generic name was kept for backwards-compatibility.

DjangoTemplates engines accept the following OPTIONS :

‘autoescape’ : a boolean that controls whether HTML autoescaping is enabled.

It defaults to True .

Only set it to False if you’re rendering non-HTML templates!

‘context_processors’ : a list of dotted Python paths to callables that are used to populate the context when a template is rendered with a request. These callables take a request object as their argument and return a dict of items to be merged into the context.

It defaults to an empty list.

See RequestContext for more information.

‘debug’ : a boolean that turns on/off template debug mode. If it is True , the fancy error page will display a detailed report for any exception raised during template rendering. This report contains the relevant snippet of the template with the appropriate line highlighted.

It defaults to the value of the DEBUG setting.

‘loaders’ : a list of dotted Python paths to template loader classes. Each Loader class knows how to import templates from a particular source. Optionally, a tuple can be used instead of a string. The first item in the tuple should be the Loader class name, and subsequent items are passed to the Loader during initialization.

The default depends on the values of DIRS and APP_DIRS .

See Loader types for details.

‘string_if_invalid’ : the output, as a string, that the template system should use for invalid (e.g. misspelled) variables.

It defaults to an empty string.

‘file_charset’ : the charset used to read template files on disk.

It defaults to ‘utf-8’ .

‘libraries’ : A dictionary of labels and dotted Python paths of template tag modules to register with the template engine. This can be used to add new libraries or provide alternate labels for existing ones. For example:

Libraries can be loaded by passing the corresponding dictionary key to the tag.

‘builtins’ : A list of dotted Python paths of template tag modules to add to built-ins . For example:

Tags and filters from built-in libraries can be used without first calling the tag.

Requires Jinja2 to be installed:

Set BACKEND to ‘django.template.backends.jinja2.Jinja2’ to configure a Jinja2 engine.

When APP_DIRS is True , Jinja2 engines look for templates in the jinja2 subdirectory of installed applications.

The most important entry in OPTIONS is ‘environment’ . It’s a dotted Python path to a callable returning a Jinja2 environment. It defaults to ‘jinja2.Environment’ . Django invokes that callable and passes other options as keyword arguments. Furthermore, Django adds defaults that differ from Jinja2’s for a few options:

  • ‘autoescape’ : True
  • ‘loader’ : a loader configured for DIRS and APP_DIRS
  • ‘auto_reload’ : settings.DEBUG
  • ‘undefined’ : DebugUndefined if settings.DEBUG else Undefined

Jinja2 engines also accept the following OPTIONS :

‘context_processors’ : a list of dotted Python paths to callables that are used to populate the context when a template is rendered with a request. These callables take a request object as their argument and return a dict of items to be merged into the context.

It defaults to an empty list.

Using context processors with Jinja2 templates is discouraged.

Context processors are useful with Django templates because Django templates don’t support calling functions with arguments. Since Jinja2 doesn’t have that limitation, it’s recommended to put the function that you would use as a context processor in the global variables available to the template using jinja2.Environment as described below. You can then call that function in the template:

Some Django templates context processors return a fixed value. For Jinja2 templates, this layer of indirection isn’t necessary since you can add constants directly in jinja2.Environment .

The original use case for adding context processors for Jinja2 involved:

  • Making an expensive computation that depends on the request.
  • Needing the result in every template.
  • Using the result multiple times in each template.

Unless all of these conditions are met, passing a function to the template is more in line with the design of Jinja2.

The default configuration is purposefully kept to a minimum. If a template is rendered with a request (e.g. when using render() ), the Jinja2 backend adds the globals request , csrf_input , and csrf_token to the context. Apart from that, this backend doesn’t create a Django-flavored environment. It doesn’t know about Django filters and tags. In order to use Django-specific APIs, you must configure them into the environment.

For example, you can create myproject/jinja2.py with this content:

and set the ‘environment’ option to ‘myproject.jinja2.environment’ .

Then you could use the following constructs in Jinja2 templates:

The concepts of tags and filters exist both in the Django template language and in Jinja2 but they’re used differently. Since Jinja2 supports passing arguments to callables in templates, many features that require a template tag or filter in Django templates can be achieved by calling a function in Jinja2 templates, as shown in the example above. Jinja2’s global namespace removes the need for template context processors. The Django template language doesn’t have an equivalent of Jinja2 tests.

Custom backends¶

Here’s how to implement a custom template backend in order to use another template system. A template backend is a class that inherits django.template.backends.base.BaseEngine . It must implement get_template() and optionally from_string() . Here’s an example for a fictional foobar template library:

See DEP 182 for more information.

Debug integration for custom engines¶

The Django debug page has hooks to provide detailed information when a template error arises. Custom template engines can use these hooks to enhance the traceback information that appears to users. The following hooks are available:

Template postmortem¶

The postmortem appears when TemplateDoesNotExist is raised. It lists the template engines and loaders that were used when trying to find a given template. For example, if two Django engines are configured, the postmortem will appear like:

Custom engines can populate the postmortem by passing the backend and tried arguments when raising TemplateDoesNotExist . Backends that use the postmortem should specify an origin on the template object.

Contextual line information¶

If an error happens during template parsing or rendering, Django can display the line the error happened on. For example:

Custom engines can populate this information by setting a template_debug attribute on exceptions raised during parsing and rendering. This attribute is a dict with the following values:

  • ‘name’ : The name of the template in which the exception occurred.
  • ‘message’ : The exception message.
  • ‘source_lines’ : The lines before, after, and including the line the exception occurred on. This is for context, so it shouldn’t contain more than 20 lines or so.
  • ‘line’ : The line number on which the exception occurred.
  • ‘before’ : The content on the error line before the token that raised the error.
  • ‘during’ : The token that raised the error.
  • ‘after’ : The content on the error line after the token that raised the error.
  • ‘total’ : The number of lines in source_lines .
  • ‘top’ : The line number where source_lines starts.
  • ‘bottom’ : The line number where source_lines ends.

Given the above template error, template_debug would look like:

Origin API and 3rd-party integration¶

Django templates have an Origin object available through the template.origin attribute. This enables debug information to be displayed in the template postmortem , as well as in 3rd-party libraries, like the Django Debug Toolbar.

Custom engines can provide their own template.origin information by creating an object that specifies the following attributes:

  • ‘name’ : The full path to the template.
  • ‘template_name’ : The relative path to the template as passed into the the template loading methods.
  • ‘loader_name’ : An optional string identifying the function or class used to load the template, e.g. django.template.loaders.filesystem.Loader .

The Django template language¶

Syntax¶

About this section

This is an overview of the Django template language’s syntax. For details see the language syntax reference .

A Django template is a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags.

A template is rendered with a context. Rendering replaces variables with their values, which are looked up in the context, and executes tags. Everything else is output as is.

The syntax of the Django template language involves four constructs.

Variables¶

A variable outputs a value from the context, which is a dict-like object mapping keys to values.

Variables are surrounded by << and >> like this:

With a context of <‘first_name’: ‘John’, ‘last_name’: ‘Doe’>, this template renders to:

Dictionary lookup, attribute lookup and list-index lookups are implemented with a dot notation:

If a variable resolves to a callable, the template system will call it with no arguments and use its result instead of the callable.

Tags provide arbitrary logic in the rendering process.

This definition is deliberately vague. For example, a tag can output content, serve as a control structure e.g. an “if” statement or a “for” loop, grab content from a database, or even enable access to other template tags.

Tags are surrounded by <% and %>like this:

Most tags accept arguments:

Some tags require beginning and ending tags:

Filters¶

Filters transform the values of variables and tag arguments.

Источник

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



Привет всем, недавно ознакомился с офф документацией по django и решил освоить удаление данных из бд методом POST ( Знаю, что в django есть такая вещь как Form, но хочу попробовать сперва сделать это сам).
Собственно при загрузке страницы получаю следуюшию ошибку:

Reverse for ‘delete’ with arguments ‘(»,)’ and keyword arguments ‘{}’ not found. 1 pattern(s) tried: [‘$delete/$’]

Вот содержание:
views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from .models import News

from django.core.urlresolvers import reverse
# Create your views here.

def news(request):
    listNews =  News.objects.all()
    context = {'listNews': listNews}
    return render(request, 'news/index.html', context)

def delete(request):
    delNews = request.POST['news']
    d = News.objects.filter(id=delNews).delete()
    return reverse('news:delete', kwargs={'news.id'})

urls.py

from django.conf.urls import url
from . import views


app_name='news'
urlpatterns = [
    url(r'^$', views.news, name='news'),
    url(r'^delete/$', views.delete, name='delete'),
]

index.html

{% if listNews %}
<form action="{% url 'news:delete' news.id %}" method="post">
{% for news in listNews %}
{% csrf_token %}
    <h4>{{news.title}}</h4>
    {{news.text}}
    {{news.author}}
    {{news.date}}
    <input type="text" name="news" id="news{{ forloop.counter }}" value="{{ news.id }}" />
    <input type="submit" />
{% endfor %}
</form>
<p>No news avaliable</p>
{% endif %}

P.S. Я осознаю, что здесь могут содержаться ошибки и другого рода, был бы очень признателен, если бы вы мне помогли.

  • Package version: 1.7.2
  • Django version: 2.1
  • Python version: 3.6.3
  • Template pack: bootstrap4

Description:

After upgrading to Django 2.1, an exception is raised when rendering some forms. The exception value is «render() got an unexpected keyword argument ‘renderer'». Maybe this has to do with the following change described in the release notes: «Support for Widget.render() methods without the renderer argument is removed.»

The traceback is as follows:

Installed Applications:
[‘prada.apps.pradaConfig’,
‘dal’,
‘dal_select2’,
‘django.contrib.admin’,
‘django.contrib.auth’,
‘django.contrib.contenttypes’,
‘django.contrib.sessions’,
‘django.contrib.messages’,
‘django.contrib.staticfiles’,
‘rest_framework’,
‘bootstrap4’,
‘crispy_forms’,
‘django_filters’]
Installed Middleware:
[‘django.middleware.security.SecurityMiddleware’,
‘django.contrib.sessions.middleware.SessionMiddleware’,
‘django.middleware.common.CommonMiddleware’,
‘django.middleware.csrf.CsrfViewMiddleware’,
‘django.contrib.auth.middleware.AuthenticationMiddleware’,
‘django.contrib.messages.middleware.MessageMiddleware’]

Template error:
In template C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagescrispy_formstemplatesbootstrap4field.html, error at line 28
render() got an unexpected keyword argument ‘renderer’
18 :
19 : {% if field|is_checkboxselectmultiple %}
20 : {% include ‘bootstrap4/layout/checkboxselectmultiple.html’ %}
21 : {% endif %}
22 :
23 : {% if field|is_radioselect %}
24 : {% include ‘bootstrap4/layout/radioselect.html’ %}
25 : {% endif %}
26 :
27 : {% if not field|is_checkboxselectmultiple and not field|is_radioselect %}
28 : {% if field|is_checkbox and form_show_labels %}
29 :
30 : {% crispy_field field ‘class’ ‘form-check-input’ %}
31 : {{ field.label|safe }}{% if field.field.required %}*{% endif %}
32 :
33 : {% include ‘bootstrap4/layout/help_text_and_errors.html’ %}
34 : {% else %}
35 :

36 : {% crispy_field field %}
37 : {% include ‘bootstrap4/layout/help_text_and_errors.html’ %}
38 :

Traceback:

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangocorehandlersexception.py» in inner
34. response = get_response(request)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangocorehandlersbase.py» in _get_response
156. response = self.process_exception_by_middleware(e, request)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangocorehandlersbase.py» in _get_response
154. response = response.render()

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplateresponse.py» in render
106. self.content = self.rendered_content

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplateresponse.py» in rendered_content
83. content = template.render(context, self._request)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplatebackendsdjango.py» in render
61. return self.template.render(context)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplatebase.py» in render
171. return self._render(context)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplatebase.py» in _render
163. return self.nodelist.render(context)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplatebase.py» in render
937. bit = node.render_annotated(context)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplatebase.py» in render_annotated
904. return self.render(context)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplateloader_tags.py» in render
150. return compiled_parent._render(context)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplatebase.py» in _render
163. return self.nodelist.render(context)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplatebase.py» in render
937. bit = node.render_annotated(context)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplatebase.py» in render_annotated
904. return self.render(context)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplateloader_tags.py» in render
62. result = block.nodelist.render(context)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplatebase.py» in render
937. bit = node.render_annotated(context)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplatebase.py» in render_annotated
904. return self.render(context)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplatedefaulttags.py» in render
309. return nodelist.render(context)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplatebase.py» in render
937. bit = node.render_annotated(context)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplatebase.py» in render_annotated
904. return self.render(context)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagescrispy_formstemplatetagscrispy_forms_tags.py» in render
199. c = self.get_render(context).flatten()

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagescrispy_formstemplatetagscrispy_forms_tags.py» in get_render
118. actual_form.form_html = helper.render_layout(actual_form, node_context, template_pack=self.template_pack)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagescrispy_formshelper.py» in render_layout
308. template_pack=template_pack

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagescrispy_formslayout.py» in render
140. return self.get_rendered_fields(form, form_style, context, template_pack, **kwargs)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagescrispy_formslayout.py» in get_rendered_fields
104. for field in self.fields

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagescrispy_formslayout.py» in
103. render_field(field, form, form_style, context, template_pack=template_pack, **kwargs)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagescrispy_formsutils.py» in render_field
62. form, form_style, context, template_pack=template_pack,

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagescrispy_formslayout.py» in render
287. fields = self.get_rendered_fields(form, form_style, context, template_pack, **kwargs)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagescrispy_formslayout.py» in get_rendered_fields
104. for field in self.fields

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagescrispy_formslayout.py» in
103. render_field(field, form, form_style, context, template_pack=template_pack, **kwargs)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagescrispy_formsutils.py» in render_field
62. form, form_style, context, template_pack=template_pack,

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagescrispy_formslayout.py» in render
361. fields = self.get_rendered_fields(form, form_style, context, template_pack, **kwargs)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagescrispy_formslayout.py» in get_rendered_fields
104. for field in self.fields

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagescrispy_formslayout.py» in
103. render_field(field, form, form_style, context, template_pack=template_pack, **kwargs)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagescrispy_formsutils.py» in render_field
148. html = template.render(context)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplatebackendsdjango.py» in render
61. return self.template.render(context)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplatebase.py» in render
171. return self._render(context)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplatebase.py» in _render
163. return self.nodelist.render(context)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplatebase.py» in render
937. bit = node.render_annotated(context)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplatebase.py» in render_annotated
904. return self.render(context)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplatedefaulttags.py» in render
309. return nodelist.render(context)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplatebase.py» in render
937. bit = node.render_annotated(context)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplatebase.py» in render_annotated
904. return self.render(context)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplatedefaulttags.py» in render
309. return nodelist.render(context)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplatebase.py» in render
937. bit = node.render_annotated(context)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplatebase.py» in render_annotated
904. return self.render(context)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplatedefaulttags.py» in render
309. return nodelist.render(context)

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangotemplatebase.py» in render
940. bits.append(str(bit))

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangoutilshtml.py» in
397. klass.str = lambda self: mark_safe(klass_str(self))

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangoformsboundfield.py» in str
33. return self.as_widget()

File «C:UsersdietmarDocumentsVisual Studio 2017Projectsfb3.netfb3netvirtenv36_64libsite-packagesdjangoformsboundfield.py» in as_widget
93. renderer=self.form.renderer,

Exception Type: TypeError at /prada/pruefung/728/
Exception Value: render() got an unexpected keyword argument ‘renderer’

This topic has been deleted. Only users with topic management privileges can see it.

  • I’m writing a Django website on the Dronov book. Using Django 3.0. And in chapter 2.7, «The follow-up is a mistake:

    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 constituent[0-9]+)/$’

    What do you do, and how can there be a mistake in line 0?

    Basic.html:

    <!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:

    {% 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 %}
    

    views.py:

    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)

    models.py

    from django.db import models
    

    class Bb(models.Model):
    title = models.CharField(max_length=50, verbose_name='Товар')
    content = models.TextField(null=True, blank=True,
    verbose_name='Описание')
    price = models.FloatField(null=True, blank=True, verbose_name='Цена')
    published = models.DateTimeField(auto_now_add=True, db_index=True,
    verbose_name='Опубликовано')

    rubric = models.ForeignKey('Rubric', null=True, on_delete=models.PROTECT, verbose_name = 'Рубрика')
    
    class Meta:
        verbose_name_plural = 'Объявления'
        verbose_name = 'Объявление'
        ordering = ['-published']
    

    class Rubric(models.Model):
    name = models.CharField(max_length=20, db_index=True, verbose_name='Название')

    def __str__(self):
        return self.name
    
    class Meta:
        verbose_name_plural = 'Рубрики'
        verbose_name = 'Рубрика'
        ordering = ['name']
    

    The error comes out on the page. django


  • rubric = models.ForeignKey('Rubric', null=True,...

    There’s probably a problem here — you might not have a shirt. Make sure you’ve got it. bb There’s a shirt, and then you get the link. Or your replacement.

    <p><a href="{% url 'by_rubric' bb.rubric.pk %}">{{ bb.rubric.name }}</a></p>
    

    Like,

    {% url 'by_rubric' bb.rubric.pk as bb_rubric_url %}
    {% if bb_rubric_url %}
    <p><a href="{{ bb_rubric_url">{{ bb.rubric.name }}</a></p>
    {% else %}
    Нет связи с рубрикой
    {% endif %}    
    

    else Added clean to see where the problem is.


  • Извините, если это нубский код или вопрос. Я делаю нумерацию страниц с использованием 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

    I’m learning Django framework and I have in the extend templates part, I’m trying to add a new template when I click in the title of the post in my blog to redirect to an page with the post details (date/author/etc),so I create a new view in views.py and a new url to in urls.py,But when I adc the path of the url in the ‘href’ desirable of the .html file ,as you will see, I receive the follow error when I reload the page:

    NoReverseMatch at /

    Reverse for ‘blog.views.post_detail’ with arguments ‘()’ and keyword
    arguments ‘{‘pk’: 2}’ not found. 0 pattern(s) tried: []

    And

    Error during template rendering

    In template
    /home/douglas/Documentos/Django/my-first-blog/blog/templates/blog/post_list.html,
    error at line 9

    So, when I erase the href to back the default value all works well…I am almost sure that something is wrong in the href line but I will post all template related files for you to check, if you need to check anything else let me know:

    firs the html file: post_list.html

    {% extends 'blog/base.html' %}
    
    {% block content %}
        {% for post in posts %}
            <div class="post">
                <div class="date">
                    {{ post.published_date }}
                </div>
                <h1><a href="{% url 'blog.views.post_detail' pk=post.pk %}">{{ post.title }}</a></h1>
                <p>{{ post.text|linebreaksbr }}</p>
            </div>
        {% endfor %}
    {% endblock content %}
    

    urls.py:

    from django.conf.urls import url
    from . import views
    from .models import Post
    
    urlpatterns = [
        url(r'^$', views.post_list),
        url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail),
    ]
    

    views.py

    from django.shortcuts import render
    from django.shortcuts import render, get_object_or_404
    from .models import Post
    from django.utils import timezone
    
    def post_list(request):
        #posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
        posts = Post.objects.all()
        return render(request, 'blog/post_list.html', {'posts': posts})
    
    def post_detail(request, pk):
        post = get_object_or_404(Post, pk=pk)
        return render(request, 'blog/post_detail.html', {'post': post})
    

    Well guys, I think is that, I hope I have not forgotten any details about my question…
    Thank you in advance,any help is welcome!!

    Понравилась статья? Поделить с друзьями:
  • 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