【发布时间】:2020-10-22 06:56:29
【问题描述】:
我正在尝试动态调用 url 的视图。 让我准确地说。 我想创建一些对象,实际上是“练习”,每个对象都需要一个视图(因为有大量的变量,这会因练习而异)。我为每个练习使用了一个 TemplateView。 其实每个人也需要不同的htlm,但是这个可以在视图中给出。
我尝试了这里找到的方法:Dynamic for url
这是我们感兴趣的代码: 我确切地说,Exercise 类的每个练习(在 models.py 中)都至少有一个名为 Wanted_view 的属性,它表示练习的所需视图。
example.html(包含练习链接):
{% for exercise in list_exercise %}
...
<a href="{% url 'vue_exercise' exercise.id exercise.wanted_view %}"> The link to the wanted exercise </a>
...
{% endfor %}
urls.py:
...
from . import views
urlpatterns = [
url(r'^exercise/(?P<exercise_id>\d+)/(?P<channel>\w+)/$', views.switcher, name='vue_exercise'),
]
这里是一个动态 url,它等待 exercise_id(这里是 exercise.id)和频道(这里是 exercise.wanted_view)。
views.py:
def switcher(request, channel):
if channel == 'TheFamousWantedView':
return TheFamousWantedView.as_view()(request)
class TheFamousWantedView(generic.TemplateView):
template_name = 'wanted_template.html'
context_object_name = ...
def get_context_data(self, **kwargs):
exercise = Exercise.objects.get(id=kwargs['exercise_id'])
context = super().get_context_data(**kwargs)
context['exercise'] = exercise
return context
这里我们建立了练习的视图,它带回了练习的id,以便能够显示一些与这个相关的具体信息。
我遇到的问题是切换器功能必须调用好的视图。 我有这个错误:
switcher() 得到了一个意外的关键字参数“exercise_id”
此外,我是否能够制作一个类似于切换器的功能,为此我不必为每个视图创建 IF 条件,例如上面的“if channel == 'TheFamousWantedView' ...)? ?
解决方案1:我以这种方式修改了我的功能
def switcher(request, niveau_id, channel):
if channel == 'TheFamousWantedView':
return TheFamousWantedView.as_view()(request)
现在调用 TheFamousWantedView,这很酷,但还有另一个问题。 kwargs 字典似乎已被清空,现在出现了一个 KeyError,它告诉我,executive_id 是未知的......在我定义该切换器函数之前,它工作得很好。
有什么想法吗??
【问题讨论】:
标签: django django-views django-templates django-urls keyerror