Django part : 4

Photo by Faisal on Unsplash

Django part : 4

Reset Django Admin Password

python manage.py changepassword <username>

Replace <username> with the username of the admin user whose password you want to reset.

You'll be prompted to enter a new password for the specified user. Follow the prompts to enter and confirm the new password.

Filter Work in Django using filter()

The filter() method is used to retrieve a subset of objects from a queryset based on specified conditions. It allows you to narrow down the queryset to only include objects that meet certain criteria.

#views.py where you run query
from myapp.models import MyModel

# Retrieve objects where the 'field1' attribute is equal to 'value1'
filtered_objects = MyModel.objects.filter(field1='value1')

# Retrieve objects where 'field2' attribute is greater than or equal to 100
filtered_objects = MyModel.objects.filter(field2__gte=100)

# Retrieve objects where 'field3' attribute contains the substring 'example'
filtered_objects = MyModel.objects.filter(field3__contains='example')

Auto SlugField - Explained with Examples in Django

A SlugField is a field used to store a URL-friendly version of string. The AutoSlugField is a convenient extension of the SlugField that automatically generates a slug based on another field in the model.

pip install django-autoslug

let's walk through an example of using AutoSlugField in Django. We'll create a simple blog application where each blog post has a title and a slug generated automatically from the title. Then, we'll set up a template with links to individual blog posts, and implement the necessary URL routing and view to display the posts.

  1. Define the Model with AutoSlugField:

     # models.py
     from django.db import models
     from autoslug import AutoSlugField
    
     class BlogPost(models.Model):
         title = models.CharField(max_length=100)
         content = models.TextField()
         slug = AutoSlugField(populate_from='title', unique=True)
    
         def __str__(self):
             return self.title
    
  2. Set Up the Template with Links:

     <!-- blog_post_list.html -->
     <!DOCTYPE html>
     <html lang="en">
     <head>
         <meta charset="UTF-8">
         <meta name="viewport" content="width=device-width, initial-scale=1.0">
         <title>Blog Post List</title>
     </head>
     <body>
         <h1>Blog Post List</h1>
         <ul>
             {% for post in posts %}
                 <li><a href="{% url 'blog_post_detail' slug=post.slug %}">{{ post.title }}</a></li>
             {% endfor %}
         </ul>
     </body>
     </html>
    
  3. Define URL Patterns:

     # urls.py (inside your app)
     from django.urls import path
     from .views import BlogPostListView, BlogPostDetailView
    
     urlpatterns = [
         path('', BlogPostListView.as_view(), name='blog_post_list'),
         path('<slug:slug>/', BlogPostDetailView.as_view(), name='blog_post_detail'),
     ]
    
  4. Create Views:

     # views.py
     def blog_post_list(request):
         posts = BlogPost.objects.all()
         return render(request, 'blog_post_list.html', {'posts': posts})
    
     def blog_post_detail(request, slug):
         post = get_object_or_404(BlogPost, slug=slug)
         return render(request, 'blog_post_detail.html', {'post': post})
    
  5. Display Individual Blog Post:

     <!-- blog_post_detail.html -->
     <!DOCTYPE html>
     <html lang="en">
     <head>
         <meta charset="UTF-8">
         <meta name="viewport" content="width=device-width, initial-scale=1.0">
         <title>{{ post.title }}</title>
     </head>
     <body>
         <h1>{{ post.title }}</h1>
         <p>{{ post.content }}</p>
         <a href="{% url 'blog_post_list' %}">Back to Blog Post List</a>
     </body>
     </html>
    

Pagination and How to Add Pagination Project

Pagination is the process of dividing a large set of content or data into discrete pages, making it easier to navigate and consume. In web development, pagination is commonly used to display a subset of items at a time, typically in a list or grid format, with navigation controls to move between pages.

  1. Paginate Queryset:

     from django.core.paginator import Paginator
     from .models import YourModel
    
     def your_view(request):
         objects_list = YourModel.objects.all()
         paginator = Paginator(objects_list, per_page)
         page_number = request.GET.get('page')
         page_obj = paginator.get_page(page_number)
         return render(request, 'your_template.html', {'page_obj': page_obj})
    
  2. Update Template:

     <!-- your_template.html -->
     <h1>Your Paginated Content</h1>
     {% for item in page_obj %}
         <!-- Display item content -->
     {% endfor %}
    
     <!-- Pagination controls -->
     <div class="pagination">
         <span class="step-links">
             {% if page_obj.has_previous %}
                 <a href="?page=1">&laquo; first</a>
                 <a href="?page={{ page_obj.previous_page_number }}">previous</a>
             {% endif %}
    
             <span class="current">
                 Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
             </span>
    
             {% if page_obj.has_next %}
                 <a href="?page={{ page_obj.next_page_number }}">next</a>
                 <a href="?page={{ page_obj.paginator.num_pages }}">last &raquo;</a>
             {% endif %}
         </span>
     </div>
    

What is TinyMCE Integration

Integrating TinyMCE into a Django project enables you to provide a powerful text editor in your web application for creating and managing rich text content, such as blog posts, articles, and more.

  1. Install Django TinyMCE Package:

     pip install django-tinymce
    
  2. Add tinymce to INSTALLED_APPS:

  3. Update Models:

     #models.py
     from django.db import models
     from tinymce.models import HTMLField
    
     class BlogPost(models.Model):
         title = models.CharField(max_length=200)
         content = HTMLField()
    
         def __str__(self):
             return self.title
    
  4. Add TinyMCE URLs:

#urls.py
from django.urls import include, path

urlpatterns = [
    ...
    path('tinymce/', include('tinymce.urls')),
]
  1. Use TinyMCE in Forms:

     #forms.py
     from django import forms
     from tinymce.widgets import TinyMCE
     from .models import BlogPost
    
     class BlogPostForm(forms.ModelForm):
         content = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30}))
    
         class Meta:
             model = BlogPost
             fields = ['title', 'content']
    

How to Save Form Data to Database

To save form data to a database in a Django project, you typically use a combination of Django forms, models, and views

  1. Define Your Model:

     # models.py
     from django.db import models
    
     class BlogPost(models.Model):
         title = models.CharField(max_length=200)
         content = models.TextField()
    
         def __str__(self):
             return self.title
    
  2. Create a Form:

     # forms.py
     from django import forms
     from .models import BlogPost
    
     class BlogPostForm(forms.ModelForm):
         class Meta:
             model = BlogPost
             fields = ['title', 'content']
    
  3. Create a View:

     # views.py
     from django.shortcuts import render, redirect
     from .forms import BlogPostForm
    
     def create_blog_post(request):
         if request.method == 'POST':
             form = BlogPostForm(request.POST)
             if form.is_valid():
                 form.save()  # Save the form data to the database
                 return redirect('blog_post_list')  # Redirect to a success page or list of blog posts
         else:
             form = BlogPostForm()
         return render(request, 'create_blog_post.html', {'form': form})
    
  4. Create a URL Pattern:

     # urls.py
     from django.urls import path
     from .views import create_blog_post
    
     urlpatterns = [
         path('create/', create_blog_post, name='create_blog_post'),
         # Other URL patterns...
     ]
    
  5. Create a Template:

     <!-- templates/create_blog_post.html -->
     <!DOCTYPE html>
     <html lang="en">
     <head>
         <meta charset="UTF-8">
         <meta name="viewport" content="width=device-width, initial-scale=1.0">
         <title>Create Blog Post</title>
     </head>
     <body>
         <h1>Create a New Blog Post</h1>
         <form method="post">
             {% csrf_token %}
             {{ form.as_p }}
             <button type="submit">Save</button>
         </form>
     </body>
     </html>