Surveyor Jr
Surveyor Jr

Reputation: 408

Save Calculated Value from View to Model in Django

I have a Django application that gives the user an option to save a calculation or not within the form.

If the user says they want to save the calculation, I would like to save the calculation result in the database too along with the input details.

For the user input I am already able to save it. The challenge comes when saving the calculated results which are being handled by the views.py.

My code is below:

for my views.py

def coordinate_transform(request):
    if request.method == 'POST':
        form = CoordinateForm(request.POST)
        if form.is_valid():
            from_epsg = request.POST.get('from_epsg')
            y = request.POST.get('y')
            x = request.POST.get('x')
            to_epsg = request.POST.get('to_epsg')
            # Transform Coordinates
            transformer = Transformer.from_crs(int(from_epsg), int(to_epsg))
            transformed = transformer.transform(y, x)
            # Save to Database? 
            save_data = request.POST.get('saved')
            if save_data == 'on':
                form.save()
                messages.success(request, "Coordinate Transormation data stored")

            context = {
                'form': form,
                'y': transformed[0],
                'x': transformed[1],
            }

            return render(request, 'utility/coordinate_transform.html', context)


    else:
        form = CoordinateForm()

    context = {
        'form': form,
    }


    return render(request, 'utility/coordinate_transform.html', context)

In the above code, form.save() is working fine but the calculation is not being saved. I tried using the Django Querysets to save the model and its not working.

Here is my model.py

class CoordinateTransform(models.Model):
    from_epsg = models.ForeignKey(CRS, on_delete=models.CASCADE, related_name='from_epsg')
    x = models.FloatField(verbose_name="X/Lon")
    y = models.FloatField(verbose_name="Y/Lat")
    to_epsg = models.ForeignKey(CRS, on_delete=models.CASCADE, related_name='to_epsg')
    x_trans = models.FloatField(verbose_name='X-Transformed', null=True, blank=True)
    y_trans = models.FloatField(verbose_name='Y-Transformed', null=True, blank=True)
    stored_on = models.DateTimeField(auto_now_add=True)

and lastly the form that I am using to collect the user input from forms.py

class CoordinateForm(ModelForm):
    # some widget stuff here
    class Meta:
        model = CoordinateTransform
        fields = ('from_epsg', 'y', 'x', 'to_epsg')

How best can I be able to make sure the calculation is also being stored in the database?

Upvotes: 2

Views: 807

Answers (1)

Brian Destura
Brian Destura

Reputation: 12078

You can defer saving the objects with form.save(commit=False), and then add the calculated fields like so:

def coordinate_transform(request):
    if request.method == 'POST':
        form = CoordinateForm(request.POST)
        if form.is_valid():
            ...
            # Save to Database? 
            save_data = request.POST.get('saved')
            if save_data == 'on':
                instance = form.save(commit=False)
                instance.x_trans = transformed[1]
                instance.y_trans = transformed[0]
                instance.save()
                messages.success(request, "Coordinate Transormation data stored")

Upvotes: 2

Related Questions