“模型对象没有属性'保存'" [英] "Model object has no attribute 'save'"

查看:36
本文介绍了“模型对象没有属性'保存'"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不知道该怎么办.如何使用post方法从表单中以SQL添加数据?

Don't know what to do with this error. How to add data in SQL from forms using post method?

models.py

models.py

class Lala(models.Model):
    PRIORITY_CHOICES = ( 
        (0, '1'),
        (1, '2'),
        (2, '3'),
        (3, '4'),
     )
    name = models.CharField(max_length=20)
    date = models.DateField()
    priority = models.CharField(max_length=1, choices=PRIORITY_CHOICES)

Views.py

def add (request):
    if request.method == 'POST': # If the form has been submitted...
        form = AddLala(request.POST) # A form bound to the POST data
        if form.is_valid():
            newform = form.save()

Form.py

class AddLala(forms.Form):
    PRIORITY_CHOICES = ( 
        (0, '1'),
        (1, '2'),
        (2, '3'),
        (3, '4'),
     )
    name = forms.CharField(max_length=100)
    date = forms.DateField()
    priority = forms.CharField(max_length=1, widget=forms.Select(choices=PRIORITY_CHOICES))

add.html

<form target="upload_frame" action="" method="post" enctype="multipart/form-data" >
 {% csrf_token %}
    {{ form.as_p }}<br>
    <input type="submit" name="submit" value="Upload" id="submit">
</form>

urls.py

  (r'^add/$', 'QA.QAtool.views.add'),
   (r'^addLala/$', 'QA.QAtool.views.addLala'),

因此,如果我继续下一步的话,可以将数据添加到数据库-只需添加

So, I can Add data to DB, if I go next way - Just add

 lala = Lala(id=None, name='teststep3', date='1943-12-12', priority='High') 
 lala.save()

我真的不明白哪里出了问题,我到处都将form.save()视为标准方法,但对我而言却不是.

I really don't understand whats wrong, everywhere I see form.save() as a Standard method, but not for me.

推荐答案

尝试使用ModelForm而不是Form:

Try using a ModelForm instead of a Form:

class Lala(models.Model):
    PRIORITY_CHOICES = ( 
        (0, '1'),
        (1, '2'),
        (2, '3'),
        (3, '4'),
     )
    name = models.CharField(max_length=20)
    date = models.DateField()
    priority = models.CharField(max_length=1, choices=PRIORITY_CHOICES)

在forms.py中:

In forms.py:

from django import forms

class LalaForm(forms.ModelForm):
    class Meta:
        model = Lala

然后在视图中您的现有代码应该(几乎)覆盖了它:

Then in the view your existing code should (pretty much) cover it:

def add (request):
    if request.method == 'POST': # If the form has been submitted...
        form = LalaForm(request.POST) # A form bound to the POST data
        if form.is_valid():
            form.save()    # saves a new 'Lala' object to the DB

此处签出ModelForm的文档.

Check out the docs for ModelForm here.

这篇关于“模型对象没有属性'保存'"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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