object has no attribute 'save' Django

前端 未结 1 2005
滥情空心
滥情空心 2020-12-15 06:17

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         


        
相关标签:
1条回答
  • 2020-12-15 06:46

    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 讨论(0)
提交回复
热议问题