0

我有表单验证:

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,
})

而且我不知道如何将数据保存到数据库中。例如,我在“名称:咖啡,类别:食物”字段的模板中输入了一些数据。那么如何将其保存在数据库中?

4

2 回答 2

0

通常的策略是在 AddForm 中实现保存数据的保存方法。在 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 方法来总结您将在文档中找到的概念。您当然可以调整它以适应您的需求。

干杯,

于 2013-08-22T10:31:24.280 回答
0

要将字段保存到数据库,请使用 aModelForm或使用 new 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'),)
于 2013-08-22T10:56:06.617 回答