我正在使用Django创建活动,每个人甚至偶尔会发布通知,告知注册参加活动的会员。所以我创建了两个模型,一个用于活动,另一个用于公告。以下是我的源代码的相关部分:
models.py
class Event(models.Model):
name = models.CharField(max_length=128, unique=True)
description = models.TextField()
slug = models.SlugField(unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Fund, self).save(*args, **kwargs)
class Announcement(models.Model):
event = models.ForeignKey(Event)
title = models.CharField(max_length=55)
body = models.TextField()
author = models.ForeignKey(UserProfile)
publish_date = models.DateTimeField(auto_now_add=True)
slug = models.SlugField(unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Message, self).save(*args, **kwargs)
views.py
def announcement(request, event_slug, announcement_slug):
context_dict = {}
event = get_object_or_404(Event, slug=event_slug)
context_dict['event'] = event
announcement = Announcement.objects.filter(slug=announcement_slug)
context_dict['announcement'] = announcement
return render(request, 'funds/announcement.html', context_dict)
urls.py
from django.conf.urls import patterns, url
from apps.funds import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^(?P<slug>[\w-]+)/$', views.fund_details, name='fund details'),
#This works:
url(r'^(?P<event_slug>[\w-]+)/(?P<share_class_slug>[\w-]+)/$', views.share_class_details, name='share class details'),
# This does not work:
url(r'^(?P<event_slug>[\w-]+)/(?P<announcement_slug>[\w-]+)/$', views.announcement, name='announcement'),
)
然而,每当我访问url(my-event / annoucement-title)时,我会得到我的base.html文件(导航栏,页眉,页脚)中的内容,但是我没有包含base.html我的'annoucement.html&#39;文件,其中的所有内容都是文本&#39; hello,world。&#39;
答案 0 :(得分:1)
当您访问my-event/annoucement-title
网址时,这将首先匹配share class details
网址格式,并且永远不会达到announcement
网址格式。要解决这个问题,您可以这样做:
url(r'^class-detail/(?P<event_slug>[\w-]+)/(?P<share_class_slug>[\w-]+)/$', views.share_class_details, name='share class details'),
url(r'^event-announcement/(?P<event_slug>[\w-]+)/(?P<announcement_slug>[\w-]+)/$', views.announcement, name='announcement'),
现在,如果您访问event-announcement/my-event/annoucement-title
,它将与announcement
网址格式匹配。