Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

django - "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="" 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...