kozmonotosman
kozmonotosman

Reputation: 68

Django Model, Forms Fields

I am struggling with django forms. I have been created model.form that its IntegerField but django takes them as string.

here is my models.py

from django.db import models


class CircuitComponents(models.Model):
    e1 = models.IntegerField()
    r1 = models.IntegerField()
    c1 = models.IntegerField()

forms.py

from django import forms

from .models import CircuitComponents


class CircuitComponentForm(forms.ModelForm):

    class Meta:
        model = CircuitComponents
        fields = '__all__'

and my views.py

from django.shortcuts import render

from .forms import CircuitComponentForm


def circuit_components_view(request):
    if request.method == 'POST':
        form = CircuitComponentForm(request.POST)

        if form.is_valid():
            form.save()
    else:
        form = CircuitComponentForm()

    e1 = request.POST.get('e1')
    c1 = request.POST.get('c1')
    r1 = request.POST.get('r1')
    context = {
        'form': form,
        'basic_circuit_result': e1 + c1 + r1
    }
    return render(request, 'basic_circuit.html', context)

There is also ss from the application. I was trying to make summing up them but result is as you can see on ss.. Can anyone help me with the thing that i am not seeing :D ? thanks in advance.. enter image description here

Upvotes: 2

Views: 64

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476503

request.POST will take everything as a string, the POST parameters are always key-value pairs where both the keys and the values are strings. It is the form that converts it to a value accordingly.

You can use the .cleaned_data attribute [Django-doc] to get the values that are determined by the form, so:

def circuit_components_view(request):
    basic_circuit_result = None
    if request.method == 'POST':
        form = CircuitComponentForm(request.POST)

        if form.is_valid():
            form.save()
            basic_circuit_result = form.cleaned_data['e1'] + form..cleaned_data['e1'] + form..cleaned_data['r1']
            
    else:
        form = CircuitComponentForm()
    
    context = {
        'form': form,
        'basic_circuit_result': basic_circuit_result
    }
    return render(request, 'basic_circuit.html', context)

Upvotes: 1

Related Questions