Я создавал приложение Django с Celery и использую Javascript для опроса локальной базы данных о статусе задачи Celery с помощью URL. По какой-то причине я продолжаю получать сообщение об ошибке из тега шаблона URL в моем скрипте. Что я делаю не так?
Я просмотрел все варианты этого вопроса на SO, и все они сводятся к дурным именам. Насколько я вижу, мои имена верны, и я не использую пространства имен.
Мой urls.py
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from django.views.generic.base import RedirectView
from django.urls import path, re_path
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
import app.views
from django.conf.urls import include
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
path('signup/', app.views.signup, name='signup'),
path('resetpassword/', auth_views.PasswordResetView.as_view(
template_name='registration/resetpassword.html'), name="resetpassword"),
path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(
template_name='registration/password_reset_done.html'), name='password_reset_done'),
path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(
template_name='registration/resetpasswordconfirm.html'), name='password_reset_confirm'),
path('reset/done/', auth_views.PasswordResetCompleteView.as_view(
template_name='registration/resetpasswordcomplete.html'), name='password_reset_complete'),
path('graph', app.views.draw_graph, name='graph'),
path('upload', app.views.upload, name='upload'),
path('download', app.views.download_zip),
path('render', app.views.render_pulses, name='render'),
path('display', app.views.display_images, name='display'),
path('render_status', app.views.render_status, name='render-status'),
path('', app.views.gallery, name='gallery'),
re_path(r'^(?P<slug>[-\w]+)$', app.views.AlbumDetail.as_view(), name='album'),
# Auth related urls
re_path(r'accounts/login/$', auth_views.LoginView.as_view(), name='login'),
re_path(r'accounts/logout/$', app.views.logout, {'next_page': '/', }, name='logout'),
# Uncomment the next line to enable the admin:
path('admin/', admin.site.urls),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
handler404 = 'app.views.handler404'
Оскорбительный Javascript (layout.html).
<script type="text/javascript">// <![CDATA[
function get_status() {
var urlStatus = '{% url "render-status" %}';
fetch().then(function(response) {
response.json().then(function(data) {
if(data.status) {
// show render link
// don't forget to hide on click
}
else {
// show loading gif
}
});
});
get_status();
// ]]></script>
Функция представлений, которая ведет к
def render_status(request):
result = db_API.get_render_status(request.user.id)
return HttpResponse({'status': result}, content_type='application/json')
Наконец, трассировка
Environment:
Request Method: GET
Request URL: https://www.echobatalog.com/
Django Version: 2.2
Python Version: 3.6.7
Installed Applications:
['app',
'material',
'material.admin',
'imagekit',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sitemaps',
'django.contrib.sites',
'django_celery_results']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'material.frontend.middleware.SmoothNavigationMiddleware']
Template error:
In template /home/batalog/batalogvenv/Bat_Echolocation_2019/app/templates/layout.html, error at line 3
Reverse for 'render-status' not found. 'render-status' is not a valid view function or pattern name.
1 : <script type="text/javascript">// <![CDATA[
2 : function get_status() {
3 : var urlStatus = ' {% url "render-status" %} ';
4 : fetch(urlStatus).then(function(response) {
5 : response.json().then(function(data) {
6 : if(data.status) {
7 : // show render link
8 : // don't forget to hide on click
9 : }
10 : else {
11 : // show loading gif
12 : }
13 : });
Traceback:
File "/home/batalog/batalogvenv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/home/batalog/batalogvenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "/home/batalog/batalogvenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/batalog/batalogvenv/Bat_Echolocation_2019/app/views.py" in gallery
File "/home/batalog/batalogvenv/lib/python3.6/site-packages/django/shortcuts.py" in render
36. content = loader.render_to_string(template_name, context, request, using=using)
File "/home/batalog/batalogvenv/lib/python3.6/site-packages/django/template/loader.py" in render_to_string
62. return template.render(context, request)
File "/home/batalog/batalogvenv/lib/python3.6/site-packages/django/template/backends/django.py" in render
61. return self.template.render(context)
File "/home/batalog/batalogvenv/lib/python3.6/site-packages/django/template/base.py" in render
171. return self._render(context)
File "/home/batalog/batalogvenv/lib/python3.6/site-packages/django/template/base.py" in _render
163. return self.nodelist.render(context)
File "/home/batalog/batalogvenv/lib/python3.6/site-packages/django/template/base.py" in render
937. bit = node.render_annotated(context)
File "/home/batalog/batalogvenv/lib/python3.6/site-packages/django/template/base.py" in render_annotated
904. return self.render(context)
File "/home/batalog/batalogvenv/lib/python3.6/site-packages/django/template/loader_tags.py" in render
150. return compiled_parent._render(context)
File "/home/batalog/batalogvenv/lib/python3.6/site-packages/django/template/base.py" in _render
163. return self.nodelist.render(context)
File "/home/batalog/batalogvenv/lib/python3.6/site-packages/django/template/base.py" in render
937. bit = node.render_annotated(context)
File "/home/batalog/batalogvenv/lib/python3.6/site-packages/django/template/base.py" in render_annotated
904. return self.render(context)
File "/home/batalog/batalogvenv/lib/python3.6/site-packages/django/template/loader_tags.py" in render
150. return compiled_parent._render(context)
File "/home/batalog/batalogvenv/lib/python3.6/site-packages/django/template/base.py" in _render
163. return self.nodelist.render(context)
File "/home/batalog/batalogvenv/lib/python3.6/site-packages/django/template/base.py" in render
937. bit = node.render_annotated(context)
File "/home/batalog/batalogvenv/lib/python3.6/site-packages/django/template/base.py" in render_annotated
904. return self.render(context)
File "/home/batalog/batalogvenv/lib/python3.6/site-packages/django/template/defaulttags.py" in render
443. url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "/home/batalog/batalogvenv/lib/python3.6/site-packages/django/urls/base.py" in reverse
90. return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "/home/batalog/batalogvenv/lib/python3.6/site-packages/django/urls/resolvers.py" in _reverse_with_prefix
660. raise NoReverseMatch(msg)
Exception Type: NoReverseMatch at /
Exception Value: Reverse for 'render-status' not found. 'render-status' is not a valid view function or pattern name.
Я ожидал, что он будет постоянно проверять мою базу данных на предмет статуса последней работы пользователей, но вместо этого он выдает ошибку.