2017-06-23 71 views
2

我正在製作一個超簡約的博客應用程序作爲第一個項目。我無法讓表單的CharField顯示在頁面上,而且我無法找到關於如何將表單數據放入我的數據庫的簡明解釋。Django 1.11:發佈表單數據到數據庫

爲清晰起見,編輯:我正在努力讓所有人都可以發佈內容,而不僅僅是具有官方教程中的管理員權限的用戶。

forms.py:

1 from django import forms                       
    2                             
    3 class ContentForm(forms.Form):                     
    4  form_post = forms.CharField(widget = forms.TextInput) 

views.py:

1 from django.shortcuts import render                    
    2 from django.http import HttpResponse                    
    3 from .forms import ContentForm                     
    4 from .models import Post                       
    5                          
    6 def post(request):                        
    7  #testvar = "TEST VARIABLE PLZ IGNORE"                  
    8  post_list = Post.objects.order_by('id')                  
    9                          
10  return render(request, 'posts/main.html',                 
11    {'post': post_list},                  
12 )                           
13                          
14 def content_get(request):                      
15                          
16  if request.method == 'POST':                     
17                          
18   form = ContentForm(request.POST)                   
19                          
20   return render(request, 'main.html', {'form':form}) 

main.html中:

1 <head>                   
    2 <h1>Nanoblogga</h1>                      
    3                            
    4 </head>                   
    5                            
    6 <body>                          
    7 {% for i in post %}                      
    8 <li>{{ i }}</li>                       
    9 {% endfor %}                        
10                            
11                            
12 <form action = '/' method = 'post'>                  
13  {% csrf_token %}                       
14  {{ form }}                        
15  <input type = 'submit' value = 'Submit' />                
16 </form>                   
17 </body> 

models.py
from django.db import models 

class Post(models.Model): 
    content = models.CharField(max_length = 200) 

    def __str__(self): 
return self.content 

我感謝你的意見。

回答

3

有你需要修改根據你的代碼很多點:

forms.py:你需要ModelForm與模型Post工作。

from django.forms import ModelForm 
from .models import Post 
class ContentForm(ModelForm): 
    class Meta: 
     model = Post 
     fields = "__all__" 

views.py:您必須將form傳遞給模板,以便它可以在你的HTML main來表現,並調用form.save()將數據保存到數據庫。

from django.shortcuts import render, redirect                    
from django.http import HttpResponse                    
from .forms import ContentForm                     
from .models import Post 

def post(request):                        
    post_list = Post.objects.order_by('id') 
    form = ContentForm() 
    return render(request, 'posts/main.html', 
     {'post': post_list, 
     'form':form}, 
    )                           
def content_get(request): 
    if request.method == 'POST': 
     form=ContentForm(request.POST) 
     if form.is_valid(): 
      form.save() 
     return redirect('/') 

假設你有應用urls.py這樣的:

from django.conf.urls import url 

from . import views 

app_name = 'post' 

urlpatterns = [ 
    url(r'^$', views.post, name='main'), 
    url(r'^content$', views.content_get, name='content_get'), 
] 

最後在main.html中,您需要定義發佈一個action

<html> 
<head>                   
<h1>Nanoblogga</h1>                      
</head>                   
<body> 
    {% for i in post %}                      
    <li>{{ i }}</li> 
    {% endfor %}   

    <form action = '/content' method ='post'> 
    {% csrf_token %} 
    {{ form }} 
    <input type = 'submit' value = 'Submit' /> 
    </form> 
</body> 
</html> 
+0

這使我重定向到/內容,我想我需要創建或更改。但它解決了我的主要問題。讚賞。 –

+0

你可以使用'redirect',它會重定向到你想要的任何url,比如main url。檢查更新的答案。 –

2
def content_get(request):                                              
    if request.method == 'POST':                                           
     form = ContentForm(request.POST) 
     if form.is_valid():               
      instance = form.save() 
      return HttpResponse('create success') 
     else: 
      return HttpResponse(forms.errors) 
    else:                    
     return render(request, 'main.html', {'form':form}) 

main.html中:

<form action = '/content_get/' method = 'post'>                  
    {% csrf_token %}                       
    {{ form }}                        
    <input type = 'submit' value = 'Submit' />                
</form>                   

注意:您需要設置表單動作方法content_get的URL。

+0

我如你所說的改變它,但我試圖保持表單提交在主頁上,而不是去一個不同的網址。我將如何實現這一目標? –