Django part : 3

Photo by Faisal on Unsplash

Django part : 3

What is Redirect and How to Redirect Page in Django

A redirect is a HTTP response that instructs the client's web browser to navigate to a different URL. Redirects are commonly used to direct users to a new page after performing a certain action, such as submitting a form, logging in, or logging out.

  1. Import the redirect shortcut: Import the redirect function from django.shortcuts at the top of your views file.

     from django.shortcuts import redirect
    
  2. Use the redirect function: Call the redirect function with the desired URL as its argument. This URL can be a URL pattern name, a relative URL, or an absolute URL.

     from django.shortcuts import redirect
    
     def my_view(request):
         # Perform some action...
         return redirect('new_page')  # Redirect to a URL pattern name
        # return redirect('/new-page/')  # Redirect to a relative URL
        # return redirect('https://example.com/')  # Redirect to an absolute URL
    
  3. Map the URL pattern: Ensure that the target URL you're redirecting to is mapped to a view in your URLconf (urls.py).

     from django.urls import path
     from .views import new_page_view
    
     urlpatterns = [
         path('new-page/', new_page_view, name='new_page'),
         # Other URL patterns...
     ]
    

What is HTML Action URL in Django

In Django, an HTML action URL refers to the URL to which a form submission will be sent when the form is submitted by the user.

In HTML forms, the action attribute specifies the URL where the form data should be submitted. When the user submits the form, the browser sends a HTTP POST request to this URL, along with the form data.

<form method="post" action="{% url 'submit_form' %}">
    {% csrf_token %}
    <!-- Form fields go here -->
    <button type="submit">Submit</button>
</form>
  • The action attribute of the form specifies {% url 'submit_form' %}, which generates the URL for the view named submit_form. This URL is determined by the URL pattern defined in your urls.py.

  • The {% csrf_token %} template tag is included inside the form to add a CSRF token, which is a security measure to protect against Cross-Site Request Forgery (CSRF) attacks.

#urls.py
from django.urls import path
from .views import submit_form_view

urlpatterns = [
    path('submit-form/', submit_form_view, name='submit_form'),
    # Other URL patterns...
]
#views.py
from django.shortcuts import render

def submit_form_view(request):
    if request.method == 'POST':
        # Process form submission
        # Retrieve form data from request.POST
        # Perform necessary actions
        return render(request, 'success.html')  # Render success page
    else:
        return render(request, 'form.html')  # Render form page

When the form is submitted, the browser will send a POST request to the URL specified in the form's action attribute (/submit-form/ in this example). Django will then route this request to the submit_form_view function, where you can process the form data and return an appropriate response.

FORM in Django

  1. Define a Form Class:

     # forms.py
     from django import forms
    
     class MyForm(forms.Form):
         name = forms.CharField(max_length=100)
         email = forms.EmailField()
    
  2. Render the Form in a Template:

     # views.py
     from django.shortcuts import render
     from .forms import MyForm
    
     def my_view(request):
         form = MyForm()
         return render(request, 'my_template.html', {'form': form})
    
     <!-- my_template.html -->
     <form method="post">
         {% csrf_token %}
         {{ form.as_p }}
         <button type="submit">Submit</button>
     </form>
    
  3. Handle Form Submission:

     # views.py
     from django.shortcuts import render, redirect
     from .forms import MyForm
    
     def my_view(request):
         if request.method == 'POST':
             form = MyForm(request.POST)
             if form.is_valid():
                 # Process form data
                 name = form.cleaned_data['name']
                 email = form.cleaned_data['email']
                 # Perform necessary actions (e.g., save to database)
                 return redirect('success_page')  # Redirect to success page
         else:
             form = MyForm()
         return render(request, 'my_template.html', {'form': form})
    
  4. Map URL to View: Ensure that the URL pattern for the view is defined in your urls.py file.

     # urls.py
     from django.urls import path
     from .views import my_view
    
     urlpatterns = [
         path('my-form/', views.my_view, name='my_form'),
         # Other URL patterns...
     ]
    

    Updated form handling process doc.

What is model and How to Create a Model in Django

In Django, a model is a Python class that represents a database table. Models define the structure and behavior of data stored in a database. Each model class corresponds to a table in the database, and each attribute of the model class represents a field in that table.

  1. Create a new Django app:

     python manage.py startapp myapp
    
  2. Define the model: In the models.py file of your newly created app (myapp/models.py), define your model class.

     # myapp/models.py
     from django.db import models
    
     class Post(models.Model):
         title = models.CharField(max_length=100)
         content = models.TextField()
         published_at = models.DateTimeField(auto_now_add=True)
    
         def __str__(self):
             return self.title
    
  3. Register the app: Open the settings.py file of your main Django project (settings.py) and add your app (myapp) to the INSTALLED_APPS list.

     # settings.py
     INSTALLED_APPS = [
         ...
         'myapp',
     ]
    
  4. Run migrations: Run the following command to create database tables for your models:

     python manage.py makemigrations
     python manage.py migrate
    
  5. Create a class for customizing the admin interface: In your admin.py file within your app directory (myapp/admin.py), create a class that inherits from admin.ModelAdmin. This class will be used to customize the display of your model in the Django admin interface.

     # myapp/admin.py
     from django.contrib import admin
     from .models import Post
    
     class PostAdmin(admin.ModelAdmin):
         list_display = ('title', 'content', 'published_at')  # Specify fields to display in list view
    
     # Register the model with the custom admin interface
     admin.site.register(Post, PostAdmin)
    
  6. Run the development server and Access the admin interface: Open a web browser and navigate to http://127.0.0.1:8000/admin/. Log in with the superuser credentials you created earlier.

you can retrieve data from a database table using model queries. The objects.all() method fetches all records from the specified model's database table. You can then pass this data to a template for display.

  1. Retrieve Data from a Table using objects.all(

     # views.py
     from django.shortcuts import render
     from .models import YourModel
    
     def your_view(request):
         data = YourModel.objects.all()
       # data_asc = YourModel.objects.all().order_by('field_name')  # Ascending order
       # data_desc = YourModel.objects.all().order_by('-field_name')  # Descending order
       # imited_data = YourModel.objects.all()[:10]  # Limiting to 10 results
         return render(request, 'your_template.html', {'data': data})
    
  2. Displaying Data in Template:

     <!-- your_template.html -->
     <ul>
     {% for item in data %}
         <li>{{ item.field_name }}</li>
     {% endfor %}
     </ul>
    

    Here:

    • data is the queryset containing multiple objects retrieved from the database using objects.all()

    • item is a temporary variable used in the for loop to iterate over each object in the data queryset.

    • {{ item.field_name }} refers to accessing the value of the field_name attribute of each individual object (item) in the queryset.