如何将数据添加到我的数据库?
我的表格:
from django import forms
class DinnerForm(forms.Form):
name = forms.CharField(max_length=100)
text = forms.CharField(max_length=255)
和型号:
class Dinner(models.Model):
name = models.CharField(max_length=100)
text = models.CharField(max_length=255)
我的观点:
def add_dinner(request):
if request.method == 'POST':
form = DinnerForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
text = form.cleaned_data['text']
如何将数据保存到数据库?
答案 0 :(得分:5)
我认为更好的选择是使用FormModels。要向数据库添加内容:
### example
def add_dinner(request):
if request.method == 'POST':
form = DinnerForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
text = form.cleaned_data['text']
diner = Dinner.objects.create(
name = name,
text = text,)
答案 1 :(得分:0)
如果你不使用ModelForm,你可以这样做:
def add_dinner(request):
if request.method == 'POST':
form = DinnerForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
text = form.cleaned_data['text']
query = Dinner(name = name , text = text)
query.save()