首页 > 解决方案 > Django 错误:找不到“作业”的反向。'jobs' 不是有效的视图函数或模式名称

问题描述

我一直在尝试在模板中显示作业列表,当我调用已归档或当前作业 url 时。仅当有一些可用作业时,我才会收到以下错误。感谢提前 回溯 环境:

Request Method: GET
Request URL: http://localhost:1000/customer/jobs/current/

Django Version: 3.2.6
Python Version: 3.9.6
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'bootstrap4',
 'social_django',
 'core.apps.CoreConfig']
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',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'core.middleware.ProfileMiddleware']


Template error:
In template C:\Users\Subash A\venvdelivo\delivo\core\templates\base.html, error at line 0
   Reverse for 'jobs' not found. 'jobs' is not a valid view function or pattern name.
   1 : <!DOCTYPE html>
   2 : <html lang="en">
   3 : <head>
   4 :     <meta charset="UTF-8">
   5 :     <meta http-equiv="X-UA-Compatible" content="IE=edge">
   6 :     <meta name="viewport" content="width=device-width, initial-scale=1.0">
   7 :     <title>Home</title>
   8 :     {% load bootstrap4 %}
   9 :     {% bootstrap_css %}
   10 :     {% bootstrap_javascript jquery='full' %}


Traceback (most recent call last):
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "C:\Users\Subash A\venvdelivo\delivo\core\customer\views.py", line 145, in current_jobs
    return render(request,'customer/jobs.html', {
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\shortcuts.py", line 19, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\backends\django.py", line 61, in render
    return self.template.render(context)
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line 170, in render
    return self._render(context)
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line 162, in _render
    return self.nodelist.render(context)
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line 938, in render
    bit = node.render_annotated(context)
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\loader_tags.py", line 150, in render
    return compiled_parent._render(context)
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line 162, in _render
    return self.nodelist.render(context)
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line 938, in render
    bit = node.render_annotated(context)
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\loader_tags.py", line 150, in render
    return compiled_parent._render(context)
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line 162, in _render
    return self.nodelist.render(context)
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line 938, in render
    bit = node.render_annotated(context)
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\loader_tags.py", line 62, in render
    result = block.nodelist.render(context)
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line 938, in render
    bit = node.render_annotated(context)
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\loader_tags.py", line 62, in render
    result = block.nodelist.render(context)
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line 938, in render
    bit = node.render_annotated(context)
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\defaulttags.py", line 312, in render
    return nodelist.render(context)
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line 938, in render
    bit = node.render_annotated(context)
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\defaulttags.py", line 211, in render
    nodelist.append(node.render_annotated(context))
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\defaulttags.py", line 446, in render
    url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\base.py", line 86, in reverse
    return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
  File "C:\Users\Subash A\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 694, in _reverse_with_prefix
    raise NoReverseMatch(msg)

Exception Type: NoReverseMatch at /customer/jobs/current/
Exception Value: Reverse for 'jobs' not found. 'jobs' is not a valid view function or pattern name.

网址.py

通过尝试,我发现只有在有工作时才会发生错误

"""delivo URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,include
from django.contrib.auth import decorators, views as auth_views
from django.urls.conf import include
from django.conf import settings
from django.conf.urls.static import static
from core import views
from core.customer import views as customer_views
from core.courier import views as courier_views
customer_urlpatterns=[
    path('',customer_views.home,name='home'),
    path('profile/',customer_views.profile_page,name='profile'),
    path('create_job/',customer_views.create_job,name='create_job'),
    path('jobs/current/',customer_views.current_jobs,name='current_jobs'),
    path('jobs/archived/',customer_views.archived_jobs,name='archived_jobs'),
    path('jobs/<job_id>/',customer_views.job_page,name='job'),


]
courier_urlpatterns=[
    path('',courier_views.home,name='home')
]
urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('social_django.urls',namespace='social')),
    path('',views.home),
    
    path('sign-in/',auth_views.LoginView.as_view(template_name="sign_in.html")),
    path('sign-out/',auth_views.LogoutView.as_view(next_page="/")),
    path('sign-up/',views.sign_up),

    path('customer/',include((customer_urlpatterns,'customer'))),
    path('courier/',include((courier_urlpatterns,'courier'))),
]

if settings.DEBUG:
    urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

客户/views.py

import requests
import firebase_admin
from firebase_admin import credentials,auth


from django.shortcuts import redirect, render
from django.contrib.auth.decorators import login_required
from core.customer import forms
from django.urls import reverse
from django.contrib import messages
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
from django.conf import settings
from core.models import *
cred = credentials.Certificate(settings.FIREBASE_ADMIN_CREDENTIAL)
firebase_admin.initialize_app(cred)
@login_required()
def home(request):
    return redirect(reverse('customer:profile'))
@login_required(login_url='/sign-in/?next=/customer/')
def profile_page(request):
    user_form=forms.BasicUserForm(instance=request.user)
    customer_form=forms.BasicCustomerForm(instance=request.user.customer)
    password_form=PasswordChangeForm(request.user)
    if request.method=="POST":
        if request.POST.get('action') =='update_profile':
            user_form=forms.BasicUserForm(request.POST,instance=request.user)
            customer_form=forms.BasicCustomerForm(request.POST,request.FILES,instance=request.user.customer)
            if user_form.is_valid() and customer_form.is_valid():
                user_form.save()
                customer_form.save()
                messages.success(request,'Your profile has been updated')
                return redirect(reverse('customer:profile'))
        elif request.POST.get('action') =='update_password':
            password_form=PasswordChangeForm(request.user,request.POST)
            if password_form.is_valid():
                user=password_form.save()
                update_session_auth_hash(request,user)
                messages.success(request,'Your password has been updated')
                return redirect(reverse('customer:profile'))
        elif request.POST.get('action') =='update_phone':
            firebase_user=auth.verify_id_token(request.POST.get('id_token'))
            request.user.customer.phone_number=firebase_user['phone_number']
            request.user.customer.save()
            return redirect(reverse('customer:profile'))

    return render(request,'customer/profile.html',{
        "user_form":user_form,
        "customer_form":customer_form,
        "password_form":password_form,
    })

@login_required(login_url='/sign-in/?next=/customer/')
def create_job(request):
    current_customer=request.user.customer
    # return render(request,'customer/create_job.html')
    has_current_job=Job.objects.filter(
        customer=current_customer,
        status__in=[
            Job.PROCESSING_STATUS,
            Job.PICKING_STATUS,
            Job.DELIVERING_STATUS,
        ]
    ).exists()
    if has_current_job:
        messages.warning(request,"You currently have a processing job.")
        return redirect(reverse('customer:current_jobs'))
    creating_job=Job.objects.filter(customer=current_customer,status=Job.CREATING_STATUS).last()
    step1_form=forms.JobCreateStep1Form(instance=creating_job)
    step2_form=forms.JobCreateStep2Form(instance=creating_job)
    step3_form=forms.JobCreateStep3Form(instance=creating_job)

    if request.method=='POST':
        if request.POST.get('step')=='1':
            step1_form=forms.JobCreateStep1Form(request.POST,request.FILES,instance=creating_job)
            if step1_form.is_valid():
                creating_job=step1_form.save(commit=False)
                creating_job.customer=current_customer
                creating_job.save()
                return redirect(reverse('customer:create_job'))
        elif request.POST.get('step')=='2':
            step2_form=forms.JobCreateStep2Form(request.POST,instance=creating_job)
            if step2_form.is_valid():
                creating_job=step2_form.save()
                return redirect(reverse('customer:create_job'))
        elif request.POST.get('step')=='3':
            step3_form=forms.JobCreateStep3Form(request.POST,instance=creating_job)
            if step3_form.is_valid():
                creating_job=step3_form.save()
                try:
                    r=requests.get("https://maps.googleapis.com/maps/api/distancematrix/json?origins={}&destinations={}&key={}".format(
                        creating_job.pickup_address,
                        creating_job.delivery_address,
                        settings.GOOGLE_MAP_API_KEY,
                    ))
                    print(r.json()['rows'])
                    distance=r.json()['rows'][0]['elements'][0]['distance']['value']
                    print(distance)
                    duration=r.json()['rows'][0]['elements'][0]['duration']['value']
                    creating_job.distance=round(distance/1000,2)
                    creating_job.duration=int(duration/60)
                    creating_job.price=creating_job.distance*4
                    if creating_job.price<20:
                        creating_job.price=20
                    creating_job.save()
                except Exception as e:
                    print(e)
                    messages.error(request,"Unfortunately we arent able to get your order,Kindly contact our fast customer care")
                return redirect(reverse('customer:create_job'))
        elif request.POST.get('step')=='4':
            creating_job.status=Job.PROCESSING_STATUS
            creating_job.save()
            return redirect(reverse('customer:home'))

    if not creating_job:
        current_step=1
    elif creating_job.delivery_name:
        current_step=4
    elif creating_job.pickup_name:
        current_step=3
    else:
        current_step=2
    return render(request,'customer/create_job.html',{
        "job":creating_job,
        "step":current_step,
        "step1_form":step1_form,
        "step2_form":step2_form,
        "step3_form":step3_form,
        "GOOGLE_MAP_API_KEY":settings.GOOGLE_MAP_API_KEY


    })

@login_required(login_url='/sign-in/?next=/customer/')
def current_jobs(request):
    jobs=Job.objects.filter(
        customer=request.user.customer,
        status__in=[
            Job.PROCESSING_STATUS,
            Job.PICKING_STATUS,
            Job.DELIVERING_STATUS
        ]
    )
    return render(request,'customer/jobs.html',{
        "jobs":jobs
    })

@login_required(login_url='/sign-in/?next=/customer/')
def archived_jobs(request):
    jobs=Job.objects.filter(
        customer=request.user.customer,
        status__in=[
            Job.COMPLETED_STATUS,
            Job.CANCELED_STATUS,
        ]
    )
    return render(request,'customer/jobs.html',{
        "jobs":jobs
    })

@login_required(login_url='/sign-in/?next=/customer/')
def job_page(request,job_id):
    job=Job.objects.get(id=job_id)
    if request.method=="POST" and job.status==Job.PROCESSING_STATUS:
        job.status=Job.CANCELED_STATUS
        job.save()
        return redirect(reverse('customer:archived_jobs'))
    return render(request,'customer/job.html',{
        "job":job,
        "GOOGLE_MAP_API_KEY":settings.GOOGLE_MAP_API_KEY
    })

标签: pythonpython-3.xdjangodjango-views

解决方案


推荐阅读