Django – show bootstrap modal after successful save data to db

Question:

I’m new to Django and at this point , I set up a very simple post article page, I hope that when I successfully save the article, it will show the message of the bootstrap modal style.

model.py

from django.db import models
from django.utils import timezone

class Article(models.Model):
    title = models.CharField(max_length=100,blank=False,null=False)
    slug = models.SlugField()
    content = models.TextField()
    cuser = models.CharField(max_length=100)
    cdate = models.DateField(auto_now_add=True)
    mdate = models.DateField(auto_now=True)

forms.py

from .models import Article
from django.forms import ModelForm


class ArticleModelForm(ModelForm):
    class Meta:
        model = Article
        fields = [
            'title',
            'content',
        ]

views.py

from django.shortcuts import render
from .forms import ArticleModelForm
from django.contrib.auth.decorators import login_required
from .models import Article

@login_required
def create_view(request):
    form = ArticleModelForm(request.POST or None)
    context={
        'form':form
    }

    if form.is_valid():
        article_obj = Article(cuser=request.user)
        form = ArticleModelForm(request.POST,instance=article_obj)
        form.save()
        context['saved']=True
        context['form']=ArticleModelForm()

    return render(request,'article/create.html',context= context)

my template > article/create.html

{% extends 'base.html' %}

{% block content %}

<form method="POST">
    {% csrf_token %}
    {{form.as_p}}
    <div><button data-bs-toggle="modal" data-bs-target="#saveModal"  type="submit">create</button></div>
</form>

{% if saved %}
<div class="modal fade" id="saveModal">
    <div class="modal-dialog">
        <div class="modal-content">
                <div class="modal-header">
                    <h3>save successfully!</h3>
                    <button type="button" class="btn-close" data-bs-dismiss="modal">
                    </button>
                </div>
        </div>
    </div>
</div>
{% endif %}
{% endblock content %}

I use the saved variable in views.py to determine whether the content of the article has been successfully saved, and if so, set it in the context

In the template if saved exists, the modal related code will be presented, but this way
unsuccessful.

Asked By: eddieW18

||

Answers:

The problem is with modal itself, whenever you are submitting the form the form gets submitted but when it comes with saved=True then also there is a need for clicking the button of modal to display the message saved successfully which is not possible. So the other alternative is to use alert classes of boostrap (you are free to apply your own styling to it but below is just an example), so try this template:

<form method="POST">
    {% csrf_token %}
    {{form.as_p}}
    <div><button type="submit">create</button></div>
</form>


{% if saved %}
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <strong>Saved successfully.</strong> 
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
        </button>
    </div>
{% endif %}

You should maintain separate conditions for GET and POST request and also do re-render the template with saved=True so try this view:

@login_required
def create_view(request):

    if request.method == "POST":
        article_obj = Article(cuser=request.user)
        form = ArticleModelForm(request.POST, instance=article_obj)
        if form.is_valid():

            form.save()
            context = {
                "form": ArticleModelForm(),
                "saved": "yes"
            }
            return render(request, "article/create.html", context)
        else:
            print("form is not valid")
    else:  # GET method
        form = ArticleModelForm()

    return render(request, 'article/create.html', {"form": form})
Answered By: Sunderam Dubey