Django模型,表单字段

问题描述

我正在为Django表格而苦苦挣扎。 我已经创建了model.form,使其具有IntegerField,但是django将其作为字符串。

这是我的模型。py

typedef struct {
    int supply;
    int totalPrice;
    double unitPrice;
} Product;

int comparator(const void * a,const void * b) {
    return (*(Product*) b).unitPrice - (*(Product*) a).unitPrice;
}

int main() {
    Product m[3] = {
        {18,75,4.17},{15,72,4.80},{10,45,4.50}
    };
    qsort(m,3,sizeof(Product),comparator);
    for (int i = 0; i < 3; i++) {
        printf("unitPrice=%f\n",m[i].unitPrice);
    }
}

forms.py

from django.db import models


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

和我的views.py

from django import forms

from .models import CircuitComponents


class CircuitComponentForm(forms.ModelForm):

    class Meta:
        model = CircuitComponents
        fields = '__all__'

应用程序中也有ss。我试图对它们进行总结,但结果如您在ss上所见。 有人可以帮我解决我没看到的:D吗?提前致谢.. enter image description here

解决方法

request.POST将一切都当作字符串,POST参数始终是键-值对,其中键和值都是字符串。它是将其相应地转换为值的形式。

您可以使用.cleaned_data attribute [Django-doc]来获取由表单确定的值,因此:

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)