【问题标题】:TypeError: context must be a dict rather than setTypeError:上下文必须是字典而不是集合
【发布时间】:2020-04-04 00:01:14
【问题描述】:

我正在尝试将这两种观点结合起来。这就是我所拥有的。 MenuView 将与 add_to_menu 相结合,这样如果 if 语句返回负数,menuview 部分仍会运行并在我的 html 页面上显示菜单。如果 if 语句是肯定的,它仍然显示菜单,但也将输入的信息添加到数据库中。我一次只能让其中一个工作。

编辑:好的,我发现我使用的只是愚蠢的空白,但我仍然在结合这两个视图时遇到问题。

Views.py:

class MenuView(ListView):
    model = Product
    template_name = 'mis446/edit-menu.html'
    context_object_name = 'show_menu'


def add_to_menu(request):

   if request.method == 'POST':
       if request.POST.get('name') and request.POST.get('price') and request.POST.get('nickname'):
        post=Product()
        post.name= request.POST.get('name')
        post.price= request.POST.get('price')
        post.slug= request.POST.get('nickname')
        post.save()
        model = Product
        context_object_name = {'show_menu'}
        return render(request, 'mis446/edit-menu.html', context_object_name)  

   else:
        model = Product
        context_object_name = {'show_menu'}
        return render(request,'mis446/edit-menu.html')

【问题讨论】:

  • context_object_name 是集合而不是字典
  • 如何将其更改为字典?

标签: python html django web-applications


【解决方案1】:

也许您应该检查缩进中的空格。我的意思是应该有一个制表符空间而不是 4 个空格,并且在您的第二个 if 语句中似乎有一个空格而不是制表符空间。考虑这样做

class MenuView(ListView):
    model = Product
    template_name = 'mis446/edit-menu.html'
    context_object_name = 'show_menu'


def add_to_menu(request):

   if request.method == 'POST':
       if request.POST.get('name') and request.POST.get('price') and request.POST.get('nickname'):
           post=Product()
           post.name= request.POST.get('name')
           post.price= request.POST.get('price')
           post.slug= request.POST.get('nickname')
           post.save()
           model = Product
           context_object_name = {'show_menu'}
           return render(request, 'mis446/edit-menu.html', context_object_name)  

   else:
        model = Product
        context_object_name = {'show_menu'}
        return render(request,'mis446/edit-menu.html')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 2019-02-01
    • 2017-10-02
    • 2021-04-25
    • 1970-01-01
    相关资源
    最近更新 更多