2015-09-06 159 views
0

我試圖在Django中設置一個表單並將數據保存到我的數據庫,而不使用ModelForm。我的表單正在工作,但我堅持的部分是如何處理表單數據並將其保存在視圖中。正如你所看到的,在'if form.is_valid()'之後:'我被困住了,無法想到正確的代碼。在Django保存表單數據

# models.py 

from django.db import models 

class Listing(models.Model): 
    business_name = models.CharField(max_length=80) 
    business_email = models.EmailField() 
    business_website = models.CharField(max_length=80) 
    business_phone = models.CharField(max_length=80) 

# forms.py 

from django import forms 

class NewBusinessForm(forms.Form): 
    business_name = forms.CharField(label='Business Name', max_length=100) 
    business_phone = forms.CharField(label='Phone Number', max_length=100) 
    business_email = forms.EmailField(label='Email Address', max_length=100) 
    business_website = forms.CharField(label='Web Site', max_length=100) 

# views.py 

from django.shortcuts import render 
from django.http import HttpResponseRedirect 
from .forms import NewBusinessForm 

def new_business(request): 
    if request.method == 'POST': 
     form = NewBusinessForm(request.POST) 
     if form.is_valid(): 
      # process form data 
      return HttpResponseRedirect('/') 

    else: 
     form = NewBusinessForm() 

    return render(request, 'directory/new.html', {'form': form}) 

回答

5

您需要創建對象並手動設置所有字段。這是一個例子。

def new_business(request): 
    if request.method == 'POST': 
     form = NewBusinessForm(request.POST) 
     if form.is_valid(): 
      # process form data 
      obj = Listing() #gets new object 
      obj.business_name = form.cleaned_data['business_name'] 
      obj.business_email = form.cleaned_data['business_email'] 
      obj.business_phone = form.cleaned_data['business_phone'] 
      obj.business_website = form.cleaned_data['business_website'] 
      #finally save the object in db 
      obj.save() 
      return HttpResponseRedirect('/') 
     .... 

請注意,如果字段值不符合約束,則保存對象可能會失敗。所以你需要照顧這一點。

+1

不要忘記導入上市模型 –

+0

這工作,謝謝!大多數人把這個邏輯放到views.py中嗎?或者更好地將它包含在forms.py中作爲一個函數? – Casey

+2

@Casey,大多數情況下這應該使用模型表單來完成。或者,如果你想要,你可以把這個邏輯放在'form.save()'方法中。 – Rohan