I am trying to update a value in my django model but its not getting updated
I have created a view that scans the report_file which is a excel sheet and checks the previous value and compares it with the new value and then calculates the percentage difference. This takes function only executes whenever the report_file gets updated. But for some reason when I try to save the percentage difference it does not get saved. My new value gets saved but the percentage does not.
And I have also kept print statements which are printing the correct values.
Below is my views.py:
@login_required(login_url='my-login')
def update_testcase(request, pk):
testcase = get_object_or_404(TestCase, pk=pk, user=request.user)
if request.method == 'POST':
form = TestCasesForm(request.POST, request.FILES, instance=testcase)
if form.is_valid():
# Save the form
form.save()
# Read the uploaded .xlsx file
excel_file = testcase.report_file.read()
# Extract the total number of test cases using the function from xlsx_utils.py
total_test_cases = extract_total_test_cases(excel_file)
print(total_test_cases)
# Calculate the percentage increase
previous_total_test_cases = testcase.total_test_cases
print(previous_total_test_cases)
if previous_total_test_cases:
percentage_increase = ((total_test_cases - previous_total_test_cases) / previous_total_test_cases) * 100
else:
percentage_increase = None
print(percentage_increase)
# Update the model instance with the total number of test cases and percentage increase
testcase.total_test_cases = total_test_cases
testcase.increase_percentage = percentage_increase
testcase.save()
return redirect('writer:my-testcases')
else:
form = TestCasesForm(instance=testcase)
context = {'UpdateTestCaseForm': form}
return render(request, 'writer/update-testcase.html', context)
below is my models.py:
class TestCase(models.Model):
title = models.CharField(max_length=150)
report_file = models.FileField(upload_to=user_directory_path,validators=[FileExtensionValidator(allowed_extensions=['xlsx'])])
date_posted = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(CustomUser, max_length=10, on_delete=models.CASCADE, null=True)
total_test_cases = models.IntegerField(null=True, blank=True)
category = models.CharField(max_length=10, choices=CATEGORY_CHOICES, null=True, blank=True)
url = models.URLField(max_length=200,null=True)
percentage_increase = models.DecimalField(
max_digits=5,
decimal_places=2,
validators=[MinValueValidator(Decimal('0.00')), MaxValueValidator(Decimal('2000.00'))],
null=True,
blank=True
)
below is forms.py:
class TestCasesForm(ModelForm):
class Meta:
model = TestCase
fields = ['title', 'report_file','category','url']