当前位置:  开发笔记 > 后端 > 正文

对象没有属性'save'Django

如何解决《对象没有属性'save'Django》经验,为你挑选了1个好方法。

不知道如何处理这个错误.如何使用post方法从表单中添加SQL数据?

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

{% csrf_token %} {{ form.as_p }}

urls.py

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

所以,我可以向DB添加数据,如果我采取下一步方式 - 只需添加

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

伙计们请帮我解决这个问题.我花了3天的时间试图弄清楚什么是错的,阅读关于djangoproject的文档等等.我真的不明白什么是错的,到处都看到form.save()作为标准方法,但不适合我.



1> Mikesname..:

尝试使用ModelForm而不是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

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

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的文档.

推荐阅读
手机用户2402852387
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有