Django 1.11: post 表单数据到数据库

Django 1.11: post form data to database

我正在制作一个超简约的博客应用程序作为第一个项目。我无法让我的表单的 CharField 显示在页面上,而且我无法找到关于如何将表单数据放入我的数据库的简明解释。

为清楚起见进行编辑:我正在努力使任何人都可以post做一些事情,而不仅仅是像官方教程中那样具有管理员权限的人。

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

感谢您的意见。

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。

根据您的代码需要修改的地方有很多:

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 传递给模板,以便它可以显示在您的 main html, 然后调用 form.save() 将数据保存到 db.

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

last in main.html,你需要定义哪个action到post:

<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>