def persist_pet(request, pet, template_name): if request.method == 'GET': pet.user_id = request.user.userprofile.id form = PetForm(instance=pet) context = { 'form': form, 'pet': pet, } return render(request, f'{template_name}.html', context) else: old_image = pet.image form = PetForm( request.POST, request.FILES, instance=pet, ) if form.is_valid(): if old_image: clean_up_files(old_image.path) form.save() Like.objects.filter(pet_id=pet.id).delete() return redirect('pet details or comment', pet.pk) context = { 'form': form, 'pet': pet, } return render(request, f'{template_name}.html', context)
def persist_painting(request, painting, template_name): if request.method == 'GET': form = PaintingForm(instance=painting) context = { 'form': form, 'painting': painting, } return render(request, f'{template_name}.html', context) else: old_image = painting.image form = PaintingForm(request.POST, request.FILES, instance=painting) if form.is_valid(): if old_image: clean_up_files(old_image.path) form.save() Like.objects.filter(painting_id=painting.id) \ .delete() return redirect('painting details or comment', pet.pk) context = { 'form': form, 'painting': painting, } return render(request, f'{template_name}.html', context)
def edit_pet(req, pk): pet = Pet.objects.get(pk=pk) if req.method == 'GET': form = PetCreateForm(instance=pet) context = { 'form': form, } return render(req, 'pet_edit.html', context=context) else: old_image = pet.image form = PetCreateForm(req.POST, req.FILES, instance=pet) if form.is_valid(): clean_up_files(old_image.path) form.save() return redirect('pet details or comment', pk) context = { 'form': form, } return render(req, 'pet_edit.html', context=context)
def persist(req, pet, html_template, redirect_url): if req.method == 'GET': context = { 'form': CreatePetForm(instance=pet) } return render(req, f'pets/{html_template}.html', context) elif req.method == 'POST': old_image = pet.image if old_image: clean_up_files(old_image.path) form = CreatePetForm(req.POST, req.FILES, instance=pet) if not form.is_valid(): context = { 'form': form } return render(req, f'pets/{html_template}.html', context) form.save() if 'edit' in req.path: return redirect(redirect_url, pet.id) return redirect(redirect_url)