我正在制作一个涉及抽认卡的学习应用程序。它分为几个科目。每个科目(生物学,物理学)都有一套甲板(unitone,unittwo)。每个牌组都有一组牌(术语和定义)。我希望我的网址看起来像 localhost:8000 / biology / unitone /但是我在将两个URL参数放在一个URL中时遇到了麻烦。
models.py
class Subject(models.Model):
subject_name = models.CharField(max_length=100)
description = models.TextField()
def __str__(self):
return self.subject_name
def get_absolute_url(self):
return reverse('card:index')
class Deck(models.Model):
deck_name = models.CharField(max_length=100)
subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
def __str__(self):
return self.deck_name
class Card(models.Model):
term = models.CharField(max_length=100)
definition = models.TextField()
deck = models.ForeignKey(Deck, on_delete=models.CASCADE)
def __str__(self):
return self.term
views.py
class IndexView(generic.ListView):
template_name = 'card/index.html'
context_object_name = 'subjects'
def get_queryset(self):
return Subject.objects.all()
class SubjectView(DetailView):
model = Subject
slug_field = "subject"
template_name = 'card/subject.html'
class DeckView(DetailView):
model = Deck
slug_field = "deck"
template_name = 'card/deck.html'
urls.py
# localhost:8000/subjects/1 (biology)
url(r'^subjects/(?P<pk>[0-9]+)/$', views.SubjectView.as_view(), name='subject')
# localhost:8000/subjects/1/1 (biology/unitone)
url(r'^subjects/(?P<pk>[0-9]+)/(?P<pk>[0-9]+)/$', views.DeckView.as_view(), name='deck'),
urls.py中的第二个网址是我遇到的问题。它不是有效的网址。
答案 0 :(得分:2)
您不能拥有多个具有相同名称的参数。您必须为每个参数指定一个唯一的名称,例如:
url(r'^subjects/(?P<pk>[0-9]+)/(?P<deck>[0-9]+)/$', views.DeckView.as_view(), name='deck'),
在DeckView
中,您可以self.kwargs['pk']
和self.kwargs['deck']
访问它们。
答案 1 :(得分:1)
有一种方法可以重写DetailViews
urls.py
url(r'^subjects/(?P<subjects>\w+)/(?P<deck>\w+)/$', views.DeckView.as_view(), name='deck'),
views.py
class DeckView(DetailView):
model = Deck
# slug_field = "deck" # you don't need it
template_name = 'card/deck.html'
def get_object(self, subjects, deck):
subject_obj = Subject.objects.filter(subject_name=subjects).first()
obj = Deck.objects.filter(subject=subject_obj,deck_name=deck).first()
return obj
def get(self, request, subjects, deck):
self.object = self.get_object(subjects, deck)
context = self.get_context_data(object=self.object)
return self.render_to_response(context)
然后访问localhost:8000/subjects/biology/unitone/