简体   繁体   English

Django Model, Forms 字段

[英]Django Model, Forms Fields

I am struggling with django forms.我正在努力解决 django forms。 I have been created model.form that its IntegerField but django takes them as string.我已经创建了 model.form 它的 IntegerField 但 django 将它们作为字符串。

here is my models.py这是我的models.py

from django.db import models


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

forms.py forms.py

from django import forms

from .models import CircuitComponents


class CircuitComponentForm(forms.ModelForm):

    class Meta:
        model = CircuitComponents
        fields = '__all__'

and my views.py和我的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.应用程序中还有 ss。 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?我试图对它们进行总结,但结果就像你在 ss 上看到的那样。任何人都可以帮助我解决我没有看到的事情:D? thanks in advance.. enter image description here在此先感谢..在此处输入图像描述

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. request.POST会将所有内容都作为字符串,POST 参数始终是键值对,其中键和值都是字符串。 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:您可以使用.cleaned_data属性 [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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM