【问题标题】:Don't manage to use a dynamic view for an url with Django不要设法对 Django 的 url 使用动态视图
【发布时间】: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 %}
其中list_exercise 是example.html 的上下文变量,其中包含Exercise 类的所有对象。

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


    【解决方案1】:
    def switcher(request, channel):
    

    此函数仅从您的 URL channel 接收一个参数,参数 exercise_id 未正确接收。无论如何你都必须处理它,即使你不打算对它做任何事情。

    def switcher(request, exercise_id, channel):
    

    对于“此外”,我认为您可以使用这些渠道创建一个模型,并拥有一个类似于 template_name 的字段。然后在你的函数中获取正确的频道后调用模板。

    【讨论】:

    • 感谢您的回答。确实,以这种方式在参数中添加executive_id 似乎使事情变得更好。但是,我在 TheFamousWantedView 的 get_context_data 中收到一个新的错误 'KeyError' 和 exercise_id... 你知道为什么吗?
    猜你喜欢
    • 1970-01-01
    • 2019-12-04
    • 2020-09-03
    • 2011-01-13
    • 1970-01-01
    • 1970-01-01
    • 2019-01-25
    • 2023-03-19
    • 2021-07-24
    相关资源
    最近更新 更多