不知道如何处理此错误。如何使用post方法从表单中添加SQL数据?
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'),
所以,我可以向DB添加数据,如果我接下来的话 - 只需添加
lala = Lala(id=None, name='teststep3', date='1943-12-12', priority='High')
lala.save()
伙计们请帮我解决这个问题。我花了3天的时间试图弄清楚什么是错的,阅读关于djangoproject的文档等等。我真的不明白什么是错的,到处都看到form.save()作为标准方法,但不适合我。
答案 0 :(得分:25)
尝试使用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
然后在视图中,您的现有代码应该(几乎)覆盖它:
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的文档。