I have a model with static values that I want to use in my model methods and 1 column with values that the user needs to insert called number_of_units
.
What I want to do is export the CostCalculator
but the value in the number_of_units
column should be taken from Django form, not from the model.
How can export the value from number_of_units
to the excel column?
The form is saved successfully and I can see value from the form in the admin panel but in Excel, I see the value 0 in all rows. It seems that it takes only fixed values that are in the model but doesn't the value from the form. How can I fix that and pass the value from the form to Excel?
forms.py
class CalculatorForm(forms.ModelForm):
number_of_units = forms.IntegerField(min_value=0)
class Meta:
model = CostCalculator
fields = ('number_of_units',)
resources.py
class CostCalculatorResource(resources.ModelResource):
related_product__title = Field(attribute='related_product__title', column_name='Product')
number_of_units = Field(attribute='number_of_units')
class Meta:
model = CostCalculator
models.py
class CostCalculator(models.Model):
related_product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True, related_name='related_product')
title_component = models.ForeignKey(CalculatorServiceComponent, on_delete=models.CASCADE, default=1)
number_of_units = models.IntegerField(default=0)
views.py
class ModelDetailView(FormMixin, DetailView):
model = Product
form_class = CalculatorForm
template_name = 'ModelDetailView.html'
def form_valid(self, form):
number_of_units = form.cleaned_data['number_of_units']
filter_qs = CostCalculator.objects.filter(related_product__slug=self.kwargs['slug'])
dataset = CostCalculatorResource().export(filter_qs, number_of_units)
form.save()
response = HttpResponse(dataset.xlsx, content_type="xlsx")
response['Content-Disposition'] = 'attachment; filename=cost_calculator.xlsx'
return response
CodePudding user response:
The issue is in the lines below:
dataset = CostCalculatorResource().export(filter_qs, number_of_units)
form.save()
You are first trying to read the database and then save the model. Since the default value of number_of_units is zero you are getting all zeros. Try saving the form first and then accessing that database.
form.save()
dataset = CostCalculatorResource().export(filter_qs, number_of_units)