2013-08-22 88 views
0

保存到數據庫中,我有表單驗證:從Django的形式

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

我daont知道如何將數據保存到數據庫中。例如,我在字段「name:cofee,category:food」中輸入模板中的一些數據。那麼如何將它保存在數據庫中呢?

+0

如果您AddForm是的ModelForm AddForm.save()應該做的。 – Jingo

回答

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方法,這樣做可以在文檔中找到概念。您當然可以調整它以適應您的需求。

歡呼聲,

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