2010-11-24 217 views
11

不知道該怎麼做這個錯誤。如何使用post方法從表單中添加SQL中的數據?對象沒有屬性'保存'Django

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'), 

所以,我可以將數據添加到數據庫中,如果我去旁邊的方式 - 只需添加

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

夥計們,請幫助我這個問題。我花了3天的時間試圖弄清楚什麼是錯誤的,閱讀關於djangoproject的文檔等。我真的不明白什麼是錯誤的,在任何地方我都將form.save()看作標準方法,但不適合我。

+1

你真的想在視圖中構建一個`AddTest`嗎? – 2010-11-24 21:27:00

+0

沒有表單動作... action ='/ add' – mossplix 2010-11-24 21:30:16

回答

20

嘗試使用,而不是一個窗體中的ModelForm:

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 here的文檔。

相關問題