Django:int()参数必须是字符串,类似字节的对象或数字,而不是'NoneType'

时间:2018-11-08 18:47:36

标签: python django

我需要制作一个模板,其中必须包含:

  • 两个具有随机生成的整数的输入
  • 供用户输入上述整数之和的输入
  • 按钮,用于检查用户的答案
  • 按钮,它创建新的随机整数

在随机创建整数之后,我的意思是将它们拉出视图,以便可以检查它们的总和。但是Django抛出异常ScanSettings settings = (new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)).build(); List<ScanFilter> filters = new ArrayList<>(); ScanFilter filter = new ScanFilter.Builder().build(); filters.add(filter); BluetoothManager bluetoothManager = (BluetoothManager) getApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE); BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter(); Intent intent = new Intent(getApplicationContext(), PendingIntentScanReceiver.class); intent.putExtra("o-scan", true); PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); bluetoothAdapter.getBluetoothLeScanner().startScan(filters, settings, pendingIntent);

如何解决此问题?

forms.py

ScanFilter filter = new ScanFilter.Builder()
        .setDeviceAddress("54:6C:0E:20:E6:1B")

        // or instead of setDeviceAddress trying this:
        .setServiceUuid(ParcelUuid.fromString("0000a1b0-0000-1000-8000-00805f9b34fb"))
        .build();
filters.add(filter);

views.py

int() argument must be a string, a bytes-like object or a number, not 'NoneType'

index.html

from django import forms


class SumForm(forms.Form):
    sum = forms.IntegerField(
        widget=forms.TextInput(attrs={'class': "form-control"}),
        label='',
        required=False
    )

追踪

from django.shortcuts import render
from .forms import SumForm


import random


def index(request):

    form = SumForm(request.POST)
    user_sum = form['sum'].value()

    if 'randomize' in request.POST:
        num1 = random.randint(10, 99)
        num2 = random.randint(10, 99)

    elif 'check' in request.POST:

        num1 = int(request.POST.get('int1'))
        num2 = int(request.POST.get('int2'))

        if int(user_sum) == num1 + num2:
            exclam = 'Right, ' + str(num1 + num2)
        else:
            exclam = 'wrong, ' + str(num1 + num2)

    return render(request, 'index.html', locals())

1 个答案:

答案 0 :(得分:0)

解决方案:

我刚刚添加了两个隐藏的输入,将生成的数据加倍,并将值拉到视图中。

views.py

elif 'check' in request.POST:

    num1 = int(request.POST.get("int1", ""))
    num2 = int(request.POST.get("int2", ""))

        if int(user_sum) == int(num1 + num2):
            exclam = 'Right, ' + str(num1 + num2)
        else:
            exclam = 'Wrong, ' + str(num1 + num2)

index.html

...
<tr>
    <input type="hidden" name="int1" value=" {{ num1 }} ">
    <input type="hidden" name="int2" value=" {{ num2 }} ">
    <td><span> {{ num1 }} </span></td>
    <td>+</td>
    <td><span> {{ num2 }} </span></td>
    <td>=</td>
    <td style="padding-top: 6px"> {{ form.as_p }} </td>
</tr>
...