2017-10-04 204 views
1

我試圖創建一個簡單的表單,它以用戶輸入的名稱和電子郵件爲例。 但我提交後,它沒有得到保存在數據庫 manage.py dumpdata顯示[]即空行。 請幫忙!無法將表單數據保存在數據庫中 - Django

models.py

class EmpD(models.Model): 
    name = models.CharField(max_length=100) 
    email=models.CharField(max_length=100) 

forms.py

class SubmitF(forms.ModelForm): 
    name = forms.CharField() 
    email= forms.CharField() 
    class Meta: 
     model = EmpD 
     fileds = '_all_' 

views.py

def submit_view(request): 
template_name = 'emp/home.html' 
redirect_url = 'emp/su.html' 
form = SubmitF() 

if request.method == 'POST': 
    form = SubmitF(request.POST) 
    if form.is_valid(): 
     form.save() 

     return HttpResponseRedirect(redirect_url) 
else: 
    return render(request, template_name, {'form': form}) 

def index(request): 
return render(request, 'emp/home.html') 

包含HTML形式:

<form action='' method="post" > 

{% csrf_token %} 
{{ form }} 

<table border="0" cellpadding="5" cellspacing="0"> 
<tr> <td style="width: 50%"> 
<label for="Name"><b>First name *</b></label><br /> 
<input name="Name" type="text" maxlength="50" style="width: 260px" /> 
</td> <td style="width: 50%"> 

</td> </tr> <tr> <td colspan="2"> 
<label for="Email_Address"><b>Email *</b></label><br /> 
<input name="Email_Address" type="text" maxlength="100" style="width: 535px" 
/> 
</td> </tr> <tr> <td colspan="2"> 



<input type="submit" value="Submit Data" /> 

</td> </tr> 
</table> 
</form> 

應用urls.py

urlpatterns = [ 
url(r'^$', views.index, name='index'), 
url(r'^$', views.submit_view, name='submit_view')] 
+0

請,固定的縮進views.py代碼,並顯示您的網址 –

+0

('的Fileds = '_all_'' - >'欄=' _all_'') – PRMoureu

+2

@PRMoureu其實它是'fields ='__all __'':) –

回答

0

建模,獨立的表單字段和用於單一形式3次是非常不好的方法。 試試這個。定義簡單模型。對於電子郵件輸入,定義電子郵件字段,表單本身進行驗證。

Models.py

class EmpD(models.Model): 
    name = models.CharField(max_length=100) 
    email = models.EmailField(null=True, blank=True) 

定義forms.py,如果要包括車型領域,只是fields='__all__'會爲你做它, 以這種形式,否則定義等領域

forms.py

class SubmitF(forms.ModelForm): 
    class Meta: 
     model = EmpD 
     fields = '__all__' 

簡單的views.py,如果請求方法是Get,表單呈現並且在Post請求中,數據傳遞給服務器。

def submit_view(request): 
    template_name = 'path_to_html' 
    redirect_url = 'your_url' 
    form = SubmitF() 

    if request.method == 'POST': 
     form = SubmitF(request.POST) 
     if form.is_valid(): 
      form.save() 
      return HttpResponseRedirect(redirect_url) 
    else: 
     return render(request, template_name, {'form': form}) 

模板結構

<form action="/your-name/" method="post"> 
    <label for="name">Your name: </label> 
    <input id="id_name" type="text" name="name" value="{{ current_name }}"> 
    <input type="submit" value="OK"> 
</form> 
+0

爲什麼你添加'login_required'? –

+0

刪除它,不管:) – Sagar

+0

我的意思是你可以爲OP創建新的麻煩,並且它在編輯的當前邏輯 –