Django/Python将表单中的数据(不使用模型)发布到MySQL数据库

2024-10-03 21:32:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将模板表单中的数据插入到MySQL数据库中,但它不起作用。在

表格:

class AddPollForm(forms.Form):
    poll_time = forms.CharField(label='Tiempo Poll', max_length=10) 
    poll_ip = forms.CharField(label='IP', max_length=50) 
    communitydata = forms.CharField(label='Community Data', max_length=100)
    snmp_oid = forms.CharField(label='OID', max_length=250)
    lastcheck = forms.CharField(label='Última Comprobación', max_length=20)

模板中的我的表单:

^{pr2}$

观点:

@csrf_exempt
def listpolls(request):
    connect_mysql = mdb.connect('****', '***', '***', 'noname_jc_sandbox')
    cursorMYSQL = connect_mysql.cursor(mdb.cursors.DictCursor)
    query = "select id,ip,polling_time,communitydata,snmp_oid,lastcheck from snmptt_listpolls order by ip desc limit 100"
    cursorMYSQL.execute(query)
    b = cursorMYSQL.fetchall()
    connect_mysql.close()

    if request.method == 'POST':

        form = AddPollForm(request.POST)

        if form.is_valid():

            poll_time = form.cleaned_data['poll_time']
            ip = form.cleaned_data['poll_ip']

            connect_mysql = mdb.connect('***', '***', '***', 'noname_jc_sandbox')
            cursorMYSQL = connect_mysql.cursor(mdb.cursors.DictCursor)
            cursorMYSQL.execute("insert into snmptt_listpolls (ip, polling_time) values (34, 34)")

            connect_mysql.commit()
            connect_mysql.close()

            return HttpResponseRedirect('listpolls.html')

        else:
            form = AddPollForm()
            return render_to_response("listpolls.html",{"buffer_data": b, 'form': form} )        

    else:
        form = AddPollForm()
        return render_to_response("listpolls.html",{"buffer_data": b, 'form': form} )    

在这里,我们从数据库中获取数据并将其显示在一个表中,这很好用。我也有表单,当我按下add时,我想向数据库添加另一行。在

字段类型为:

| id            | int(11)      | NO   | PRI | NULL    | auto_increment |
| ip            | varchar(50)  | NO   |     | NULL    |                |
| polling_time  | int(10)      | NO   |     | NULL    |                |
| communitydata | varchar(100) | NO   |     | NULL    |                |
| snmp_oid      | varchar(250) | YES  |     | NULL    |                |
| lastcheck     | datetime

Tags: ipformtimeconnectmysqlformsnulllength
1条回答
网友
1楼 · 发布于 2024-10-03 21:32:09

最后,这是我需要的台词,但我无法到达那里,而且我不知道如何更好地解释自己。总之,我找到了我的答案,以防万一,这里是:

cursorMYSQL.execute("""insert into snmptt_listpolls (ip, polling_time, communitydata, snmp_oid) values ('%s','%s','%s','%s')"""%(ip, poll_time, communitydata, snmp_oid))

相关问题 更多 >