0

I'm making a simple web server to take html input data and insert it to data base table .

I've tried with POST request got into more CSRF troubles , Turned to GET request to go over CSRF (not necessary in my case ) , still not able to GET the html data into Database .

myapp/models.py

from django.db import models


class Post(models.Model):
    title = models.CharField(max_length=300, unique=True)
    content = models.TextField()

myapp/templates/createpost.html

<head>
<title>Create a Post </title>
</head>

<body>
<h1>Create a Post </h1>
<form action="" method="GET">
    {%csrf_token%}
    Title: <input type="text" name="title"/><br/>
    Content: <br/>
    <textarea cols="35" rows="8" name="content">
        </textarea><br/>
    <input type="submit" value="Post"/>
</form>
</body>

</html>

myapp/views.py

from django.shortcuts import render
from .models import Post


def createpost(request):
    if request.method == 'GET':
        if request.GET.get('title', None) and request.GET.get('content', None):
            post = Post()
            post.title = request.GET.get('title', None)
            post.content = request.GET.get('content', None)
            post.save()
        return render(request, 'createpost.html')
    else:
        return render(request, 'createpost.html')

urls.py

from django.contrib import admin
from django.urls import path, include
from django.views.generic.base import TemplateView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', TemplateView.as_view(template_name='createpost.html'), name='createpost'),
]

am using Django 2.2.6 with PyCharm community 2019.2.3 I've been searching for almost 2 days , checked django doc , and stackoverflow answers , none was helpful , I had to ask to make sure its not a version related issue and forgive me if i miss understand a simple point am just a beginner.

8
  • have you tried printing this? request.GET.get('title', None) is it empty or None? what do you get? Commented Oct 2, 2019 at 9:47
  • i have no idea how to do that , i ve tried python manage.py runserver and then call the view.py on another terminal and i could not , i tried to add print command to the view and i get no output at all Commented Oct 2, 2019 at 9:54
  • ok, what I meant is, do print(request.GET.get('title', None)) and submit the form again and check Commented Oct 2, 2019 at 9:56
  • i did , and there is no print at all , all i get is my GET request [02/Oct/2019 03:00:01] "GET /?csrfmiddlewaretoken=Q0FAgroc1JbIOfKImoTIcMiX4qv1AGVYIy9quUdPSu16ttR1NGRvQFhvEK3IBa6o&title=george&content=george++++++++ HTTP/1.1" 200 440 which am trying to extract title and content from . Commented Oct 2, 2019 at 10:01
  • Show your URLs. Almost certainly you are not sending to the createpost view. But you should be using POST here anyway. Commented Oct 2, 2019 at 10:26

1 Answer 1

2

I've tried with POST request got into more CSRF troubles , Turned to GET request to go over CSRF (not necessary in my case ) , still not able to make it .

Ok.

STOP EVERYTHING RIGHT NOW

Now

  1. do the official Django tutorial and learn to use Django forms and modelforms
  2. read the HTTP spec about the proper use of GET requests (hint: the important word here is "idempotent")
  3. fix your code accordingly
  4. if by then you still have issues with the csrf token, come back and post a question about it (with a proper MCVE etc).

Also note that your question should be claused as either unclear or OT since you didn't explain what your problem is (hint: "doesn't work" doesn't explain anything). But anyway...

What you want (nb: models unchanged) is:

myapp/forms.py

from django import forms
from . models import Post

class PostForm(forms.ModelForm):
    class Meta(object):
        model = Post
        fields = ("title", "content")

views.py

from django.shortcuts import redirect, render
from . models import Post
from . forms import PostForm

def createpost(request):
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            form.save()
            # read the doc for `redirect` and change the destination to
            # something that makes sense for your app.
            # as to why we redirect, cf  https://en.wikipedia.org/wiki/Post/Redirect/Get
            return redirect("/")

    else:
        # GET request, present an empty form
        form = PostForm() 
    return render(request, 'createpost.html', {"form": form})

urls.py

from django.contrib import admin
from django.urls import path, include

# NB: actually you should define myapp's urls in 
# myapp/urls.py and `include` them here
from myapp.views import createpost

urlpatterns = [
    path('admin/', admin.site.urls),
    path('/', createpost, name='createpost'),
]

myapp/templates/createpost.html

<head>
  <title>Create a Post </title>
</head>

<body>
  <h1>Create a Post </h1>
  <form action="" method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Post"/>
   </form>
</body>

</html>

I can't garantee this will work out of the box (I'd have to post a full project with proper settings etc to be sure - and actually to test it at least once for typos etc) but that's the correct way of doing things.

I've been searching for almost 2 days

That's 2 days wasted, that you would have better used doing the official Django tutorial. I also suggest you learn to debug programs - just adding a couple ̀print("XXX")` calls in your view and checking your devserver's outputs would have made clear why nothing got created in your database (hint: with your original urls.py, you are NEVER calling your view function).

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the advice , i have read a lot of the doc .djangoproject but not as a series just a few topic related , i thought i had a good background apparently not . i've tried to debug with print , but had no idea how to call django view function .
@George that's why you should really to do the (whole!) tutorial first - it guides you into creating a simple project, so you can get the whole picture before diving into deeper details. The only caveats are the tutorial insistance on using generic class-based views (which are most of the time nothing but a useless complication that only confuses beginners), and the fact it doesn't present django forms and modelforms (which are actually a very important part of Django).
yes , i totally agree now , your answer was more helpful than 2 days random reading and searching . i ll follow the tutorial for now . and really thanks for spending your time to help a beginner like me .
@George you're welcome. I kindly suggest you also take time to learn basic debugging technics (how to trace code execution, inspect current program state etc - IOW using the step debugger), this will save you a lot of time when things don't work as expected - which is, actually, the most common case ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.