Django Form请求不将数据保存到db [英] Django Form request not saving data to db

查看:214
本文介绍了Django Form请求不将数据保存到db的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在atemplate中使用django表单来保存输入到数据库的数据。
在我看来,请求发出后,响应重定向正确,但数据不保存到db。

I am using a django form in atemplate to save data entered to database. In my view after the request is made, the response is redirected correctly but the data is not saved to db.

我可能会缺少一些东西。

I might be missing something. but am unable to find it even after a lot of debugging.

这里是到目前为止所做的:

here is what has been done so far:

views.py:

from .models import testmodel

def testview(request):
    if request.method== 'POST':
        form=MapForm(request.POST)
        if form.is_valid():
            test1=request.POST.get('t1')
            print meaningid1
            test2=request.POST.get('t2')
            print meaningid2
            pobj=testmodel(test1=test1,test2=test2)
            pobj.save()
        return HttpResponse('Successful')

已显示成功

 <form action="/testview/" method="post"> {% csrf_token %}
 {{form.as_p}}
 <input type="text" name="t1" value='' id='t1'/> <br><br><br>
  <input type="text" name="t2" value='' id='t2'/><br>
  <input type="submit" value="Submit" />
 </form>

来自forms.py:

from forms.py:

from .models import testmodel


class MapForm(forms.ModelForm):

    class Meta:
        model = testmodel
        fields = ['test1','test2']



在窗体中它将页面/ testview和页面上显示消息。但是从后端数据没有保存到db。
可以有人建议可以做什么

after the data is entered in form it is going to page /testview and showing message on page. but from backend data is not been saved to db. Can some one suggest what could be done

感谢

推荐答案

在python中,缩进很重要。

In python, indentation matters.

def testview(request):
    if request.method== 'POST':
        form=MapForm(request.POST)
        if form.is_valid():
            test1=request.POST.get('t1')
            print meaningid1
            test2=request.POST.get('t2')
            print meaningid2
            pobj=testmodel(test1=test1,test2=test2)
            pobj.save()
        return HttpResponse('Successful')

在上面的代码中,Successful实际上是否成功。你需要把你的return语句向右推四个空格,并且你还需要添加一个else子句来处理表单无效的情况。通常这只是为了再次显示表单(如果使用 form.as_p form.as_table

In the above code 'Successful' will be displayed regardless of whether the form is actually successful or not. You need to push your return statement four spaces to the right, and you also need to add an else clause which handles the situation where the form is not valid. Typically that is just to display the form again (with form errors which wil be displayed for you automatically is you use form.as_p or form.as_table)

这篇关于Django Form请求不将数据保存到db的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆