开发者

"Model object has no attribute 'save'"

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

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开发者_JAVA百科="" 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()

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


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)

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

Check out the docs for ModelForm here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜