我有表单验证:
def contact(request):
if request.method == 'POST':
form = AddForm(request.POST)
if form.is_valid():
#Saving to database
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = AddForm() # An unbound form
return render(request, 'contact.html', {
'form': form,
})
我不知道如何将数据保存到数据库中。例如,我在字段“name:cofee,category:food”中的模板中输入一些数据。那么如何将其保存在数据库中呢?
答案 0 :(得分:0)
通常的策略是在AddForm中实现一个保存数据的save方法。 在save方法中验证数据的有效性是一种很好的做法:这样您就不需要明确地调用is_valid()方法(访问errors属性将触发基本django表单类中实现的清理和验证过程) )
def contact(request):
if request.method == 'POST':
form = AddForm(request.POST)
try:
form.save()
except:
#handle exceptions
return HttpResponseRedirect('/thanks/')
else:
form = AddForm()
return render(request, 'contact.html', {'form': form,})
# save method to put in your form class
def save(self):
if not self.errors:
to_save = ObjModel(<name_of_the_object_model_field> = self.cleaned['<name_of_your_form_field_containing_the_data>'])
to_save.save()
这是描述通用django方法来完成您在文档中找到的汇总概念。您当然可以调整它以适应您的需求。
欢呼声,
答案 1 :(得分:0)
要将字段保存到数据库,请使用ModelForm
,或使用新的CreateView
,这更简单:
在views.py
:
from django.views.generic.edit import CreateView
from django.views.generic.base import TemplateView
from django.core.urlresolvers import reverse_lazy
from yourapp.models import SomeModel
class CreateSomeModel(CreateView):
model = SomeModel
template_name = 'some_template.html'
success_url = reverse_lazy('home')
class Home(TemplateView):
template_name = 'home.html'
在some_template.html
:
<form method="post">
{% csrf_token %}
{{ form }}
<input type="submit">
</form>
在home.html
:
<strong>This is the home page</strong>
在urls.py
:
from django.conf.urls import patterns, url
from yourapp.views import CreateSomeModel
from yourapp.views import Home
urlpatterns = patterns('',
url(r'^create/$', CreateSomeModel.as_view(), name='create'),
url(r'^$', Home.as_view(), name='home'),)