Home > Blockchain >  In Django, how can I have a function where I can only update the value instead of creating a new ins
In Django, how can I have a function where I can only update the value instead of creating a new ins

Time:11-16

For example, I have a function in my views.py to post availability of food. However, I do not want the user to keep creating new instances of available food. I only want the user to be able to update that value. Right now, I have restricted the user to just create a food availability instance and then am not allowing the user to create another one. However, I do not want it as such; I want the user to be able to just update that number.

This is what I have now:

def check_existing_post(request):
    data = request.POST.copy()
    data["author"] = request.user
    if len(Food_Avail.objects.filter(author=request.user)) > 0:
        return False
    else:
        return True


def post_available_food(request):
    instance = Food_Avail()
    data = request.POST.copy()
    data["author"] = request.user
    form = FoodAvailForm(data or None, instance=instance)
    if request.POST and form.is_valid() and check_existing_post(request):
        form.save()
        return HttpResponseRedirect(reverse("accounts:home"))
    else:
        messages.info(
            request, "food availability by restaurant has already been posted!"
        )
    return render(request, "food_avail/post_food_avail.html", {"food": form})

CodePudding user response:

You can fetch the object that belongs to that user, and pass it as instance=… to the form:

from django.shortcuts import get_object_or_404, redirect
from django.contrib.auth.decorators import login_required

@login_required
def post_available_food(request):
    instance = get_object_or_404(Food_Avail, author=request.user)
    if request.method == 'POST':
        form = FoodAvailForm(request.POST, request.FILES, instance=instance)
        if form.is_valid():
            form.save()
            return redirect('accounts:home')
    else:
        form = FoodAvailForm(instance=instance)
        )
    return render(request, 'food_avail/post_food_avail.html', {'food': form})

Note: Models in Django are written in PascalCase, not snake_case, so you might want to rename the model from Food_Avail to FoodAvail.


Note: You can limit views to a view to authenticated users with the @login_required decorator [Django-doc].

  • Related