Adam Silver
Adam Silver

Reputation: 93

Django 1.11: post form data to database

I am making a super-minimalistic blogging application as a first project. I'm having trouble getting my form's CharField to show up on the page, and I'm having trouble finding a concise explanation as to how I'd put that form data into my database.

Edit for clarity: I'm trying to make it so that anyone can post something, not just someone with admin privileges like in the official tutorial.

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

I appreciate your input.

Upvotes: 3

Views: 3979

Answers (2)

Tiny.D
Tiny.D

Reputation: 6556

There are lots of points you need to amend based on your code:

forms.py: you need ModelForm to work with model Post.

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

views.py: you have to pass the form to template so that it can be showed in your main html, and call form.save() to save data into 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('/')

suppose you have app urls.py like this:

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, you need to define which action to 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>

Upvotes: 4

Ykh
Ykh

Reputation: 7717

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>                                                                        

Note:you need to set form action to method content_get's url.

Upvotes: 2

Related Questions