【问题标题】:CreateView switch modelCreateView 切换模型
【发布时间】:2021-10-09 12:28:08
【问题描述】:

我的 CreateView 有问题。 我希望我可以有两种不同的模型,它们会根据它找到的 url 进行更改。 我的success_url也有问题,不知道怎么传参数。

url.py

path('crea-<tipo>', CreaView.as_view(), name="crea")

views.py

class CreaView(StaffMixin, CreateView, tipo):
  if tipo == "gruppo":
    model = Gruppi
  elif tipo == "esercizio":
    model = Esercizio
  fields = '__all__'
  template_name = 'staff/crea.html'
  success_url = '/backoffice/lista/<tipo>'

【问题讨论】:

    标签: django create-view


    【解决方案1】:

    只需创建两个不同的 CreateView:

    GruppiCreateView(StaffMixin, CreateView):
         model = Gruppi
         fields = '__all__'
         template_name = 'staff/crea.html'
         success_url = '/backoffice/lista/gruppi'
    
    EsercizioCreateView(StaffMixin, CreateView):
        model = Esercizio
        fields = '__all__'
        template_name = 'staff/crea.html'
        success_url = '/backoffice/lista/esercizio'
    

    【讨论】:

    • 对于 url.py 我是否总是需要创建两条路由?
    • 是的,在这种情况下这是最好的解决方案。除非你要复制几十个创建视图,否则这里不需要优化。
    • 好的,非常感谢您的帮助,您一直很友善 =)
    猜你喜欢
    • 2013-04-06
    • 2020-05-03
    • 2014-09-20
    • 1970-01-01
    • 2012-01-03
    • 1970-01-01
    • 2014-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多