我可以在一个视图类中组合视图函数吗?

时间:2017-12-04 11:18:57

标签: django python-3.x

下面我列出了我目前正在使用的两个视图功能。我在想,既然两个函数都在同一个模板上运行,那么组合它们是明智的。我可以在这些函数上面放一个类装饰器吗?功能是否仍然相同?

我的主要观点是,一个函数只接受'request',但另一个函数在其函数中接受'request和'slug'。

choose

@login_required(login_url='/')
def choose(request):
    if request.method == 'POST':
        print(request.POST.get)

        # Make a shoplist model instance,
        # define title,
        # define user as author,
        # define slug,
        # save budget value from the Budget view
        # save dagen value from the Budget view
        # save shoplist

        shoplist = Shoplist()
        shoplist.title = str(make_aware(datetime.now(), timezone=None, is_dst=None))
        shoplist.author = request.user
        shoplist.slug = slugify(str(shoplist.author) + '-' + shoplist.title)
        shoplist.budget = request.POST.get('budget')
        shoplist.dagen = request.POST.get('dagen')
        shoplist.vegetarisch = request.POST.get('vegetarisch')
        shoplist.save()

        # Get recipes from database and POST data form previous view
        if request.POST.get('vegetarisch') == 'True':
            recipes = Recipe.objects.filter(vegetarisch=True).all()
        else:
            recipes = Recipe.objects.all()
        budget = shoplist.budget
        dagen = shoplist.dagen
        template = loader.get_template('recipes/choose.html')
        c = {'object_list': recipes, 'budget': budget, 'dagen': dagen}
        return HttpResponse(template.render(c))

    else:
        return HttpResponseNotAllowed('GET')

add_to_shoplist

@login_required(login_url='/')
def add_to_shoplist(request, slug):

    # Get the shoplist that is made in the choose view and add the selected recipe
    latest_list = Shoplist.objects.filter(author=request.user).latest('id')
    current_recipe = Recipe.objects.filter(slug=slug).get()
    latest_list.recipes.add(current_recipe.id)

    # Add the ingredients of the selected recipe to the shoplist
    for ingredient in current_recipe.ingredients.all():
        list_ingredient = ingredient
        latest_list.ingredients.add(list_ingredient.id)

    ingredients = current_recipe.ingredients.all()
    template = loader.get_template('recipes/choose.html')

    if Shoplist.objects.filter(author=request.user).latest('id').vegetarisch == True:
        recipes = Recipe.objects.filter(vegetarisch=True).all()
    else:
        recipes = Recipe.objects.all()
    c = {'object_list': recipes, 'ingredient_list': ingredients}
    return HttpResponse(template.render(c))

1 个答案:

答案 0 :(得分:0)

我还没有找到我想解决这个问题的方法,但我得出结论,我需要使用多个视图函数,并以某种方式生成可以在同一页面上显示的多个模板/扩展。每当我找到合适的方法时,我都会尝试更新它。