2017-12-04 3 views
1

以下、現在私が扱っている2つのビュー関数を取り上げました。私は、両方の機能が同じテンプレートで動作するので、それらを組み合わせることが賢明であると考えていました。これらの関数の上にクラスデコレータを置くことはできますか?機能はまだ同じですか?1つのビュークラスでビュー関数を組み合わせることはできますか?

私の主なポイントは、1つの機能は「要求」しか受けないが、もう1つはその機能で「要求」と「スラグ」を取ります。

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)) 
+0

私はあなたが1つのテンプレートに対して異なるコンテキストを使用するのを見ることができるので、2つのテンプレートを[extend](https://docs.djangoproject.com/en/1.11/ref/templates/language/#テンプレート)、imho。 –

+0

それはクラスベースにしないでくださいが、私は両方の機能を別の拡張を与える? –

答えて

0

私はこの問題を解決する方法はまだ判明していないが、私は、私は複数のビュー機能を使用する必要があるという結論になってきました何とか同じページに表示できる複数のテンプレート/拡張を生成します。私は適切な方法を見つけるたびにこれを更新しようとします。

関連する問題