Skip to main content

Django Blog CRUD (Step-by-Step)





πŸš€ Django Blog CRUD (Step-by-Step)

1️⃣ Model (models.py)


πŸ‘‰ Idi mana database structure
πŸ‘‰ Title, content, image, date store avutayi


2️⃣ Forms (forms.py)




πŸ‘‰ Easy ga form generate cheyadaniki use avutundi


3️⃣ Views (views.py)

from django.shortcuts import render, redirect, get_object_or_404
from .models import Blog
from .forms import BlogForm

# READ (List)
def blog_list(request):
    blogs = Blog.objects.all().order_by('-created_at')
    return render(request, 'blog_list.html', {'blogs': blogs})


# CREATE
def blog_create(request):
    form = BlogForm(request.POST or None, request.FILES or None)
    
    if form.is_valid():
        form.save()
        return redirect('blog_list')

    return render(request, 'blog_form.html', {'form': form})


# UPDATE
def blog_update(request, pk):
    blog = get_object_or_404(Blog, pk=pk)
    form = BlogForm(request.POST or None, request.FILES or None, instance=blog)

    if form.is_valid():
        form.save()
        return redirect('blog_list')

    return render(request, 'blog_form.html', {'form': form})


# DELETE
def blog_delete(request, pk):
    blog = get_object_or_404(Blog, pk=pk)

    if request.method == "POST":
        blog.delete()
        return redirect('blog_list')

    return render(request, 'blog_confirm_delete.html', {'blog': blog})


4️⃣ URLs (urls.py)



5️⃣ Templates

πŸ“„ blog_list.html

<h1>All Blogs</h1>

<a href="{% url 'blog_create' %}">Create New Blog</a>

{% for blog in blogs %}
    <div>
        <h2>{{ blog.title }}</h2>
        <p>{{ blog.content|truncatewords:20 }}</p>

        {% if blog.image %}
            <img src="{{ blog.image.url }}" width="200">
        {% endif %}

        <br>
        <a href="{% url 'blog_update' blog.pk %}">Edit</a>
        <a href="{% url 'blog_delete' blog.pk %}">Delete</a>
    </div>
    <hr>
{% endfor %}


πŸ“„ blog_form.html

<h1>Blog Form</h1>

<form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}

    <button type="submit">Save</button>
</form>


πŸ“„ blog_confirm_delete.html

<h2>Are you sure you want to delete "{{ blog.title }}"?</h2>

<form method="POST">
    {% csrf_token %}
    <button type="submit">Yes, Delete</button>
</form>

<a href="{% url 'blog_list' %}">Cancel</a>


6️⃣ Media Settings (IMPORTANT)


# settings.py

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# main urls.py

from django.conf import settings
from django.conf.urls.static import static

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Comments

Popular posts from this blog

“Password Reset in Django – Complete Guide”

  Password Reset in Django – Complete Guide πŸ” Introduction Web applications lo Password Reset feature chala important. User password marchipothe, easy ga recover chesukovadaniki use avutundi. Real-time lo: Gmail Facebook Instagram anni password reset system use chestayi. ⚙️ How Password Reset Works? πŸ‘‰ Step-by-step flow: User “Forgot Password” click chestadu Email enter chestadu System reset link send chestundi User link open chestadu New password set chestadu πŸ‘‰ Idi secure ga untundi because: Token based verification Time limit untundi ⚙️ Django Password Reset Code 1️⃣ settings.py (EMAIL Setup) # settings.py EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' πŸ‘‰ Dev lo console lo email link chupistundi πŸ‘‰ Production lo Gmail SMTP use cheyachu 2️⃣ urls.py from django . urls import path from django . contrib . auth import views as auth_views urlpatterns = [ path ( 'password-reset/' , auth_v...

Python Day 5 – If Else Conditions

  🐍 Python Day 5 – If Else Conditions 🧠 Introduction 🐍 Python Day 5 – If Else Conditions Ippati varaku manam operators nerchukunnam. I roju manam decision making (If-Else) nerchukundam. πŸ‘‰ Program lo condition base chesi decisions tiskovadaniki use avutundi πŸ’‘ Example: Age 18 kanna ekkuva unte → eligible Lekapothe → not eligible πŸ”Ή Basic If Condition age = 20 if age > 18 : print ( "Eligible" ) πŸ”Ή If-Else Condition age = 16 if age >= 18 : print ( "Eligible" ) else : print ( "Not Eligible" ) πŸ”Ή If-Elif-Else marks = 75 if marks >= 90 : print ( "Grade A" ) elif marks >= 60 : print ( "Grade B" ) else : print ( "Grade C" ) πŸ§ͺ Real Example (User Input) age = int ( input ( "Enter your age: " )) if age >= 18 : print ( "You can vote ✅" ) else : print ( "You cannot vote ❌" ) ⚠️ Important Points πŸ‘‰ Indentation (space) very import...

Python Day 8 – Lists

  🧠 Introduction 🐍 Python Day 8 – Lists Ippati varaku manam functions nerchukunnam. Eroju manam Lists gurinchi nerchukundam. πŸ‘‰ List ante multiple values ni okesari store cheyadaniki use avutundi πŸ’‘ Example: Shopping items list laga πŸ“¦ πŸ”Ή Create List numbers = [ 1 , 2 , 3 , 4 , 5 ] names = [ "Manju" , "Ravi" , "Kiran" ] πŸ”Ή Access List (Index) print ( numbers [ 0 ]) # 1 print ( names [ 1 ]) # Ravi πŸ‘‰ Index always 0 nundi start avutundi ⚠️ πŸ”Ή Add Elements numbers . append( 6 ) print ( numbers ) πŸ”Ή Remove Elements numbers . remove( 3 ) print ( numbers ) πŸ”Ή Loop Through List for i in numbers : print ( i ) πŸ”Ή List Length print ( len ( numbers )) πŸ”Ή Slicing print ( numbers [ 1 : 4 ]) πŸ§ͺ Real Example marks = [ 80 , 90 , 75 , 60 ] for m in marks : if m >= 75 : print ( "Pass:" , m ) 🎯 Mini Practice names = [ "A" , "B" , "C" ] names . append( "D...