对象没有属性“保存”Django [英] object has no attribute 'save' Django

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

问题描述

不知道该怎么处理这个错误。如何使用Post方法从表单中添加数据?

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()

有人请帮我解决这个问题。我花了3天试图弄清楚什么是错误的,在djangoproject上阅读文档等等。我真的不明白什么是错误的,我看到form.save()作为一个标准的方法,但不是我的。

Guys please help me with this issue. I spent 3 days trying to figure out whats wrong, reading documentation on djangoproject, etc. 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:

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.

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

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