命名空间问题。两个不同的Url呈现相同的视图

时间:2017-02-04 22:48:41

标签: python django django-templates django-views

我的网址有问题。我有一个名为用户的应用程序有两个模型,沙龙和造型师。网址/造型师和/沙龙渲染相同的视图(stylist_results)然而/沙龙应该渲染salon_results,我无法弄清楚为什么。我认为我使用命名空间的方式可能有问题。

用户/ urls.py

from django.conf.urls import url

#import views from the current directory
from . import views

urlpatterns=[
    url(r'^$', views.stylist_results, name='stylist_results'),
    url(r'^(?P<pk>\d+)$', views.stylist_detail, name='stylist_detail'),
    url(r'^$', views.salon_results, name='salon_results'),
    url(r'^(?P<pk>\d+)$', views.salon_detail, name='salon_detail'),
]

用户/ views.py

from django.shortcuts import get_object_or_404, render

from .models import Salon, Stylist
# Create your views here.

def salon_results(request):
    salons = Salon.objects.all()
    return render(request, 'salons/salon_results.html', {'salons': salons})


def salon_detail(request, pk):
    salon = get_object_or_404(Salon, pk=pk)
    return render(request, 'salons/salon_detail.html', {'salon': salon})


def stylist_results(request):
    stylists = Stylist.objects.all()
    return render(request, 'stylists/stylist_results.html', {'stylists': stylists})

def stylist_detail(request, pk):
    stylist = get_object_or_404(Stylist, pk=pk)
    return render(request, 'stylists/stylist_detail.html', {'stylist': stylist})

urls.py

from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

from . import views

urlpatterns = [
    url(r'^salons/', include('users.urls', namespace='salons')),
    url(r'^stylists/', include('users.urls', namespace='stylists')),
    url(r'^admin/', admin.site.urls),
    url(r'^$', views.home, name='home'),
]


urlpatterns += staticfiles_urlpatterns()

views.py

from django.shortcuts import render


def home(request):
    return render(request, 'home.html')

3 个答案:

答案 0 :(得分:1)

您在这里为沙龙和造型师指定了相同的网址集(users.urls):

url(r'^salons/', include('users.urls', namespace='salons')),
    url(r'^stylists/', include('users.urls', namespace='stylists')),

答案 1 :(得分:1)

将造型师和沙龙视图分成两个独立的模块。您可以考虑创建两个不同的应用程序,但不必这样做。

用户/ stylist_urls.py

urlpatterns = [
    url(r'^$', views.stylist_results, name='stylist_results'),
    url(r'^(?P<pk>\d+)$', views.stylist_detail, name='stylist_detail'),
]

用户/ salon_urls.py

urlpatterns = [
    url(r'^$', views.salon_results, name='salon_results'),
    url(r'^(?P<pk>\d+)$', views.salon_detail, name='salon_detail'),
]

然后使用新模块更新项目的urls.py

urlpatterns = [
    url(r'^salons/', include('users.salon_urls', namespace='salons')),
    url(r'^stylists/', include('users.stylist_urls', namespace='stylists')),
    ...
]

目前,沙龙网址的正则表达式与造型师网址完全相同,因此沙龙网址将始终首先匹配。

答案 2 :(得分:0)

你期望发生什么

您在urls.py中包含相同的用户/ urls.py

它确实如下:

找我/造型师/ =&gt;进入包含网址           找到首次出现的网址(r&#39; ^ $&#39;,views.stylist_results,name =&#39; stylist_results&#39;),

呈现该视图

同样的事情发生在/ salons /

URL Dispatcher documentation