在Django中创建URL的正确方法

时间:2016-02-24 13:29:28

标签: python django django-urls

在Django我有我的应用程序,我可以在这里放置有关这些国家的国家和城市的信息。这是我的model.py文件:

class Country(models.Model):
        class Meta:
                verbose_name_plural = u'Countries'

        name = models.CharField(max_length=50)
        slug = models.CharField(max_length=255)
        description = models.TextField(max_length=10000, blank=True)

        def __unicode__(self):
                return self.name

class City(models.Model):
        class Meta:
                verbose_name_plural = u'Cities'

        name = models.CharField(u'city', max_length=200)
        slug = models.CharField(max_length=255, blank=True)
        description = models.TextField(max_length=10000, blank=True)
        country = models.ForeignKey('Country', blank=True, null=True)

        def __unicode__(self):
                return self.name

我有我的国家的详细视图,在这个视图中有一个这个国家的城市列表(views.py):

def CountryDetail(request, slug):
        country = get_object_or_404(Country, slug=slug)
        list_cities = City.objects.filter(country=country)
        return render(request, 'country/country.html', {'country':country, 'list_cities':list_cities})

这是我的urls.py:

url(r'^(?P<slug>[-_\w]+)/$', views.CountryDetail, name='country'),

我想创建一个城市网址,其中包含一个国家的slu and和一个城市的slu ,,例如domain.com/spain/barcelona/

所以我创建了城市的详细视图,它看起来像这样:

def CityDetail(request, resortslug):
        country = Country.objects.get(slug=countryslug)
        city = get_object_or_404(City, country=country, slug=cityslug)
        return render(request, 'country/city.html', {'country':country, 'city':city})

这是我对城市细节的urls.py:

url(r'^(?P<countryslug>[-_\w]+)/(?P<cityslug>[-_\w]+)$', views.CityDetail, name='resort'),

这就是我在链接到城市的国家/地区的html文件详细信息中的样子:

<h1>{{country.name}}</h1>
<p>{{country.description}}</p>
<h2>Cities</h2>
{% for city in list_cities %}
   <a href="/{{country.slug}}/{{city.slug}}">
      <p>{{city.name}}</p>
   </a>
{% endfor %}

但是当我点击该城市网址的链接时,我收到404错误。

Page not found (404)
Request Method: GET
Request URL:    http://domain.com/spain/barcelona
Using the URLconf defined in myproject.urls, Django tried these URL patterns, in this order:
The current URL, spain/barcelona, didn't match any of these.

这是我项目中的url.py

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^country/', include('country.urls')),

请帮助我理解为什么会这样,谢谢。

1 个答案:

答案 0 :(得分:3)

由于您的项目在country/前缀下包含了应用的网址,因此该城市页面可用country/spain/barcelonahttp://domain.com/country/spain/barcelona

相关问题