Tuesday, April 22, 2025

Django To-Do - Add New Post

You are advised to check corresponding YouTube video at the end of this article.

In views.py we need dedicated function that will submit things from our form into database:


from django.shortcuts import render, redirect
from .models import Posts

def index(request):
    all_posts = Posts.objects.all()[:10]
    context = {'all_posts' : all_posts}
    return render (request, 'index.html', context)

def details(request, id):
    one = Posts.objects.get(id=id)
    context = {'one' : one}
    return render (request, 'details.html', context)

def add(request):
    if(request.method == 'POST'):
        title = request.POST['title']
        text = request.POST['text']
        action = Posts(title = title, text = text)
        action.save()
        return redirect('index')
    else:
        return render(request, 'add.html')

def admin(request):
    response = redirect('admin')
    return response

The view function is called add, and it takes a request object as its argument. The function checks whether the HTTP request method is POST, which indicates that the form has been submitted with new post data.

If the request method is POST, the function retrieves the title and text fields from the request object using the request.POST dictionary. It then creates a new Posts object with the specified title and text fields, and saves it to the database using the save() method. Finally, it redirects the user to the index view function to display the updated list of posts.

If the request method is not POST, the function simply renders the add.html template, which displays a form for creating new posts.

This view function allows users to submit new posts to the database via a form, and redirects them back to the index page to see the updated list of posts.

That's it. Now you can add New Posts to a database.

Sure, you can grab this source and turn it into big site with a little bit of custom CSS, or if you are short on time, just use Bootstrap or some other frontend framework.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...