Goal/tl;dr I want to call my added method from views.py when you submit the forum and use the stuff from the textfield to make a new post object.
I am new to django, and I have looked through other stack posts, but most of these errors seem to be for cookies or users. I have also looked at the python documentation as most people have suggested, but I haven't seen all the pieces together and I am not sure how to get the textfield from the forum. Correct code and/or and explanation of what I am doing wrong and how to do it would be much appreciated.
models.py
from django.db import models
class Post(models.Model):
text = models.TextField(max_length=250)
time = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.text
views.py
from django.http import Http404, HttpResponse
from django.shortcuts import render_to_response, redirect
from blog.models import Post
from django.core.context_processors import csrf
def home(request):
try:
p = Post.objects.all()
except Post.DoesNotExist:
raise Http404
return render_to_response('index.html',
{'post':p})
def post(request, uID):
try:
p = Post.objects.get(pk=uID)
except:
raise Http404
return render_to_response('post.html',
{'post':p})
def delete(request, uID):
try:
p = Post.objects.get(pk=uID).delete()
except:
raise Http404
return render_to_response('delete.html',
{'post':p})
def new(request):
context = {}
context.update(csrf(request))
return render_to_response('new.html', context)
def added(request):
if request.method == 'POST':
context = {}
context.update(csrf(request))
p = Post.objects.create(text=request.text)
p.save()
return render_to_response("index.html", context)
else:
raise Http404
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'blog.views.home', name='home'),
url(r'^(?P<uID>\d+)/$', 'blog.views.post', name='Post Id'),
url(r'^(?P<uID>\d+)/delete/$', 'blog.views.delete', name='del'),
url(r'^new/$', 'blog.views.new'),
url(r'^created/$', 'blog.views.added'),
# url(r'^myApp/', include('myApp.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
)
new.html
<html>
<body>
<h2> Create a new Post </h2>
<form method="post" action="/created/">
{% csrf_token %}
Body: <input type="textarea" name="text">
<input type="submit" value="Submit">
</form>
</body>
</html>
You mean request.POST['text']
.
You should probably investigate the forms framework though.