Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Create Post with Input Data | Request Handling
Django: First Dive

book
Create Post with Input Data

Note

The presented code for the task is part of the framework and cannot work separately, so errors will be received when you try to Run Code. Use the Submit Task button to solve this task.

Aufgabe

Swipe to start coding

Now, let's improve our view to save new posts in the database!

The received context via HTTP request is the request.POST dictionary. The keys of the dictionary is:

python
"csrfmiddlewaretoken"
"title"
"text"

Write the View functionality for the POST method with data extracting:

  1. Save the request.POST dictionary into the data variable.

  2. Create the Post class instance named new_post

  3. Assign attributes title and text from data dictionary to the new_post instance.

  4. Save changes in the database.

  5. Return the HttpResponse object passing
    "<h1>Complete!</h1>"!

Lösung

from django.http import HttpResponse
from django.shortcuts import render

from new_app.models import Post


def post_create(request):
if request.method == "GET":
return render(request, "post_create.html")

if request.method == "POST":
data = request.POST
new_post = Post()

new_post.title = data["title"]
new_post.text = data["text"]

new_post.save()

return HttpResponse("<h1>Complete!</h1>")

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 6. Kapitel 4
from django.http import HttpResponse
from django.shortcuts import render

from new_app.models import Post


def post_create(request):
if request.method == "GET":
return render(request, "post_create.html")

if request.method == "POST":
___ = request.___
___ = Post()

new_post.title = ___["title"]
new_post.text = data["___"]

new_post.___()

return HttpResponse("___")

Fragen Sie AI

expand
ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

some-alt