コード例 #1
0
def add_modify(request):
    """
    Perform the update/creation of an ingredient with information in POST
    :param request: the http request
    :return:the ingredient view filled with the created/updated ingredient
    """
    ingredient = Ingredient()
    if ('add' == request.POST['action'] and request.user.has_perm('cooking.add_ingredient')) or (
                    'modify' == request.POST['action'] and request.user.has_perm('cooking.change_ingredient')):
        if 'add' == request.POST['action']:
            ingredient.created = timezone.now()
        else:
            ingredient = get_object_or_404(Ingredient, pk=request.POST['id'])
        ingredient.name = request.POST['name']
        ingredient.type = request.POST['type']
        ingredient.modified = timezone.now()
        ingredient.user_mod = request.user.username
        ingredient.save()
        recipes = set(IngredientRecipe.objects.filter(ingredient=ingredient).order_by('-recipe__name'))
        context = {
            'ingredient': ingredient,
            'recipes': recipes,
        }
        return render(request, 'ingredient.html', context)
    else:
        context = {
            'latest_ingredients': Ingredient.objects.order_by('-created')[:10],
            'error_messages': (_('Insufficient privileges'),),
        }
    return render(request, 'ingredients.html', context)