gpt4 book ai didi

django - "Model object has no attribute ' 保存 '"

转载 作者:行者123 更新时间:2023-12-03 13:57:53 27 4
gpt4 key购买 nike

不知道如何处理这个错误。如何使用 post 方法从表单中添加 SQL 数据?
模型.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)
View .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()
表格.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))
添加.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>
网址.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()
我真的不明白出了什么问题,我到处都看到 form.save() 作为标准方法,但不适合我。

最佳答案

尝试使用 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

然后在 View 中,您现有的代码应该(几乎)覆盖它:
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 的文档.

关于django - "Model object has no attribute ' 保存 '",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4271686/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com