复杂的网址django

时间:2016-02-24 21:17:44

标签: python django url

我想创建一个这样的网址:

example.com/reviews/state/city/school/program

州,城市,学校和计划必须从模型中动态生成。我一直在谷歌搜索,但我不知道正确的问题。我陷入了僵局。直到我解决这个问题,我真的不知道如何写任何视图或urls.py

提前感谢您的帮助。

编辑:我已经阅读了关于编写网址的教程。但是,我不想在我的正则表达式中使用数字。我想从模型字段动态生成URL。我该怎么做?

App Models

from django.db import models

import numpy as np

class State(models.Model):
    short_name = models.CharField('State abbreviation', max_length=2)
    name = models.CharField('State Name', max_length=15)

    def __str__(self):
        return self.name

class City(models.Model):
    state = models.ForeignKey(State)
    name = models.CharField('City', max_length=100)

    class Meta:
        verbose_name = 'City'
        verbose_name_plural = 'Cities'

    def __str__(self):
        return self.name

class ZipCode(models.Model):
    city = models.ForeignKey(City)
    code = models.CharField(max_length=5)

    def __str__(self):
        return self.code

class Address(models.Model):
    street = models.CharField(max_length=255, default='')
    zip_code = models.ForeignKey(ZipCode, default='')

    def __str__(self):
        return self.street

    class Meta:
        verbose_name = 'Address'
        verbose_name_plural = 'Addresses'

class Program(models.Model):
    program_type = models.CharField(max_length=3)

    def __str__(self):
        return self.program_type

class Specialty(models.Model):
    specialty = models.CharField('Specialty', max_length=30, default='')

    def __str__(self):
        return self.specialty

class School(models.Model):
    program = models.ForeignKey(Program, default='')
    specialty = models.ForeignKey(Specialty, default='', null=True)
    address = models.ForeignKey(Address, default='')
    school_name = models.CharField(max_length=100, default='')
    created = models.DateTimeField('Date published')

    def __str__(self):
        return self.school_name

    class Meta:
        verbose_name = 'School'
        verbose_name_plural = 'Schools'

1 个答案:

答案 0 :(得分:2)

您可以尝试在urls.py

中创建如下所示的网址
urls.py
# dont forget import views
urlpatterns = [
    url(r'^reviews/(?P<state>[a-z]+)/(?P<city>[a-z]+)/(?P<school>[a-z]+)/(?P<program>[a-z]+)/$',
        views.reviews, name='reviews')
]

你的views.py应该是这样的:

view.py
def reviews(request, state=None, city=None, school=None, program=None):
    # do something