Django - 将模型名称从 url 传递给视图
Posted
技术标签:
【中文标题】Django - 将模型名称从 url 传递给视图【英文标题】:Django - Passing the model name to a view from url 【发布时间】:2014-07-03 13:03:17 【问题描述】:我将如何做到这一点,以便我可以将模型名称作为 url 中的参数传递给视图?我想重用这个视图,只传递模型名称以显示参数是什么模型的列表。
这就是我目前所拥有的
查看
class ModelListView(ListView,objects):
model = objects
template_name = "model_list.html"
def get_context_data(self,**kwargs):
context = super(ModelListView, self).get_context_data(**kwargs)
context['listobjects'] = model.objects.all()
return context
网址
url(r'^musicpack', MusicPackListView.as_view(), name='musicpack-list', objects = 'MusicPack'),
url(r'^instruments', MusicPackListView.as_view(), name='instrument-list', objects = 'Instrument'),
已回答
谢谢你的回答
我已经完成了以下操作,它似乎有效。
查看
class ModelListView(ListView):
template_name = "model_list.html"
def get_context_data(self,**kwargs):
context = super(ModelListView, self).get_context_data(**kwargs)
return context
网址
#models
from inventory.views import MusicPack
from inventory.views import Instrument
#views
from inventory.views import ModelListView
url(r'^musicpacks', ModelListView.as_view(model = MusicPack,), name='musicpack-list'),
url(r'^instruments', ModelListView.as_view(model = Instrument,), name='instrument-list'),
【问题讨论】:
【参考方案1】:我会将参数从 url 传递到如下视图:
观看次数:
class ModelListView(ListView):
model = None
model_name= ''
object = None
template_name = "model_list.html"
def get_context_data(self,**kwargs):
context = super(ModelListView, self).get_context_data(**kwargs)
context['listobjects'] = model.objects.all()
return context
网址:
url(r'^musicpack', ModelListView.as_view( model= MusicPackList,model_name= 'music_pack_list' object = 'MusicPack')),
url(r'^instruments', ModelListView.as_view( model=InstrumentPackList,model_name= 'instrument_pack_list', object= 'InstrumentPack'))
【讨论】:
以上是关于Django - 将模型名称从 url 传递给视图的主要内容,如果未能解决你的问题,请参考以下文章
Urls.py 无法将#(pound) 字符传递给 Django 中的视图,
如何将一些信息传递给视图而不将其包含在 URL 中(django 新手)