Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to see if username already exists in UserCreationField - Django
I am creating a simple registration field in Django for my website. I want to see if a username already exists and display an error if it does. For example, if I had an account with the username of hi, and another user tried to create an account with the username of hi, after they click on the submit button, I want to raise an error. Right now, if I was to create an account with a username that already exists, Django will not create the account but does not display an error. My code is down bellow. Views.py def index(request,*args, **kwargs): return render(request, "index.html", {} ) def register(request, ): form = CreateUserForm() if request.method == "POST": form = CreateUserForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been successfully created, {username} ') return redirect('login') context = {'form': form} return render(request, "register.html", context ) def login(request,): return render(request,"login.html") Forms.py class CreateUserForm(UserCreationForm): username = forms.CharField(required=True, max_length=30, ) email = forms.EmailField(required=True) first_name = forms.CharField(required=True, max_length=50) last_name = forms.CharField(required=True, max_length=50) class Meta: model = User fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2',] I don't know if you need this but here is my register.html: <!--Might need to inherit from base.html--> … -
save() prohibited to prevent data loss due to unsaved related object 'log'
I am new to django.. I cannot understand what is this error. Can someone help me solve this issue? Traceback (most recent call last): File "C:\Error logger\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Error logger\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Error logger\errorLogger\log\views.py", line 130, in add_solution s.save() File "C:\Error logger\errorLogger\log\models.py", line 41, in save super().save(*args, **kwargs) File "C:\Error logger\venv\lib\site-packages\django\db\models\base.py", line 682, in save self._prepare_related_fields_for_save(operation_name='save') File "C:\Error logger\venv\lib\site-packages\django\db\models\base.py", line 932, in _prepare_related_fields_for_save raise ValueError( Exception Type: ValueError at /add-solution/4/my-name-is-anirudh Exception Value: save() prohibited to prevent data loss due to unsaved related object 'log'. Also can someone explain what does the below do? I found that this is needed for slug urls.. But I don't understand what is super().save() def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.solution) super().save(*args, **kwargs) Also what is the error that I am getting? models.py class Solutions(models.Model): log = models.ForeignKey( Log, on_delete=models.CASCADE, blank=True, null=True) solution = models.TextField(null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=50, null=False, blank=True) image = models.ImageField( upload_to='images', blank=True) def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.solution) super().save(*args, **kwargs) class Meta: verbose_name = ("Solution") verbose_name_plural = ("Solutions") def __str__(self): return f" {self.solution} " views.py def … -
Django ManyToManyField post not working in drf
model class DesignerProduct(models.Model): title = models.CharField(max_length=500, default=None) descripton = models.CharField(max_length=500, default=None) price = models.CharField(max_length=500, default=None) editions = models.CharField(max_length=500, default=None) verified = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) user = models.ForeignKey( to=Login, on_delete=models.CASCADE, related_name="designerproduct", null=True, blank=True ) collection = models.ForeignKey( to=DesignerCollection, on_delete=models.CASCADE, related_name="designerproduct", null=True, blank=True ) categories = models.ManyToManyField(DesignerCategories, related_name='designerproduct', blank=True) serializers class DesignerProductSeriali designerproductmedia = DesignerProductMediaSerializer(many=True, read_only=True) user = serializers.PrimaryKeyRelatedField(queryset=Login.objects.all(), many=False) collection = serializers.PrimaryKeyRelatedField(queryset=DesignerCollection.objects.all(), many=False) user_name = serializers.CharField(source='user.name', read_only=True) user_photo = serializers.CharField(source='user.display_photo', read_only=True) class Meta: model = DesignerProduct fields = ('id', "user", "categories", "collection", 'created_at', 'designerproductmedia', 'title', 'descripton', 'price', 'editions', 'verified', 'user_name', 'user_photo') depth = 1 data after upload { "id": 11, "user": 9, "categories": [], "collection": 6, "created_at": "2021-06-05T17:03:52.807755Z", "designerproductmedia": [ { "file": "designer/products/74647.jpg", "id": "38", "firework": null } ], "title": "hello there", "descripton": "hello there", "price": "10", "editions": "10", "verified": false, "user_name": "soubhagya pradhan", "user_photo": "profile/52319.jpg" } Here i am omplmenting django manyToMany relation and sending categories like [1, 2, 3] But, after successfull post category list comes empty . How to fix that ? Please take a look In drf also not showing please check this image -
How to style django forms
I'm using the django standar forms, is there any way to style this without using model forms class DeliveryForm(forms.Form): full_name = forms.CharField(max_length=50) email = forms.EmailField() phone = forms.CharField(max_length=25) address = forms.CharField(max_length=100) city = forms.CharField(max_length=50) postal = forms.CharField(max_length=10) this is my template as well <form action ="" method='post'> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Next"> </form> -
Adding Context to Navbar HTML Django Project
I am trying to add context to navbar.html but it is not rendering/ showing the required information. Here is the models.py: class Information(models.Model): github = models.URLField(blank=True, null=True) linkedin = models.URLField(blank=True, null=True) facebook = models.URLField(blank=True, null=True) twitter = models.URLField(blank=True, null=True) here is the view.py: #Trial 1 def home(request): template_name = 'blog/navbar.html' info = Information.objects.first() context = { 'info': info, } return render(request, template_name, context) #Trial 2 class Home(DetailView): model = Information template_name = 'blog/navbar.html' # <app>/<model>_<viewtype>.html context_object_name = 'info' Here is the HTML: <a href="" class="nav-link waves-effect">{{info.facebook}} <i class="fab fa-facebook-f"></i> </a> My Qustion: Why is the {{info.facebook}} not printing what am I missing? How should I fix it? In the URLs I did not add anything because I am sending the context to navbar which will be appearing on every page not a specific page -
How to customise the validation rules of django-allauth Login/Signup forms?
I am using django-allauth for the user authentication part of my application. I wanted to customise the validation rules for my login, ex. blacklisting certian domain name for email id. But I am not able to figure out how should I do that. I tried to make a custom login form(inherited from forms.Form class) and write the rules in that, but I guess think that allauth processes the login request with its adapter. Due to this I was getting a TypeError: __init__() got an unexpected keyword argument 'request'. I am not able to understand the flow in which the methods are being called in the adapter. Please help me implement the custom validation rules in django-allauth forms. Or else how should I inherit the LoginForm class in the allauth package so that I can add my validation rules. -
How do I integrate base.html in the main page
Im having trouble extending base.html. ill have the templates below but the problem is the webpage only shows the base.html template when i extend base.html to the main page which is item_list.html and it doesnt show the content i have on the main page. Thank you in advance for any form of guidance item_list.html {% extends "base.html" %} {% block content %} <h2> Here is the list of items </h2> {% for item in items %} {{ item }} {% endfor %} {% endblock content %} base.html <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> </body> </html> -
Formatting in Django models
I am working in django where the I have some models in my model.py file and accordingly data is added by the django-admin and the data is kind of in the type of the messages we receive in messengers i.e, It has some properties like: 1.part of the text is a link. 2.part of the text is in bold/italic. For formatting the messages like this, is there any way we can implement this or any preexisting Field like this? (Where I can style my text accordingly like the way whatsapp works i.e, it detects the links and gives ability to bold, italicize the text etc...) -
Redirecting user to dynamic url after google login using django allauth
I am using google sign in to authenticate users using django allauth. There is no need to log the user in prior to them trying to interact with the website, which happens at https://www.example.com/example/5 where 5 is just an id to a model instance in my database. After user login, I would like to redirect the user to the same page they are on. Would it be possible to do this either through passing the model id (5 in this example) through the google credentials and receive the number back at the /accounts/google/login/callback/ callback, or something similar? Or perhaps there is way using django allauth. This question is close to what I need, but I don't know how to get access to the model ID using this approach. Django-Allauth, Multiple login redirect url # In myapp/adapter.py from allauth.account.adapter import DefaultAccountAdapter class AccountAdapter(DefaultAccountAdapter): def get_login_redirect_url(self, request): url = super(AccountAdapter, self).get_login_redirect_url(request) user = request.user ''' # pseudocode, change it to actual logic # check user role and return a different URL role = get_user_role(user) if role == 'student': url = student_login_redirect_url if role == 'teacher': url = teacher_login_redirect_url ''' return url # settings.py ACCOUNT_ADAPTER = 'my_app.adapter.AccountAdapter' -
Display django field choices in a particular order
I am using django models and one of the charfields has a list of choices like class Ster(models.Model): STER_PRODUCTS_CATEGORY = [ ('Steam', 'Steam'), ('ETO', 'ETO'), ('Plasma', 'Plasma'), ('LTSF', 'LTSF'), ('Heat', 'Heat') ] ster_prod_name = models.CharField(max_length=100) ster_prod_category = models.CharField( max_length=100, choices=STER_PRODUCTS_CATEGORY, default='None') Whenever I add an item to any of the category, that particular category is shown first on the webpage. For ex, if i add an item to the category Heat, that category is displayed first. I am looping through the list. My views.py function looks like this ster_catprods = Ster.objects.values('ster_prod_category', 'id') ster_cats = {ster_item['ster_prod_category'] for ster_item in ster_catprods} for ster_cat in ster_cats: ster_prod = Ster.objects.filter(ster_prod_category=ster_cat) m = len(ster_prod) mSlides = m // 4 + ceil((m / 4) - (m // 4)) ster_prods.append([ster_prod, range(1, mSlides), mSlides]) My HTML Template snippet is like this <section class="container"> <h4 style="margin: 1em auto">1.STER</h4> <div class="row"> {% for p,range,mSlides in ster_prods %} <div class="col-xs-12 col-sm-6 col-md-4 col-lg-4 col-xl-4" data-aos="zoom-in-up" style="margin: 1em auto"> <h4 class="category-title my-4">{{p.0.ster_prod_category | safe}}</h4> {% for i in p %} <h6 class="product_title">{{i.ster_prod_name | safe }}</h6></a> {% endfor %} </div> {% endfor %} </div> </section> how do i get to display the categories in a particular order like the way i want? The … -
Filter django models by field and include data with null field
I have the dataset where i need to fetch some articles by companies, but also in same query i need to fetch data which have company = null. Basically fetch company = 1 or company = null I tried something like this but filter does not recognize None and just skip. # example 1 Article.objects.filter(company__in=[1, None]) I tried something like this and this works, but i need something like example above, because i have framework for filtering which takes dict as custom filters, so i need key value pairs. # example 2 Article.objects.filter(Q(company_id=1) | Q(company=None)) Is there any way i achive something like example 1 or some similar solutions? EDIT: If im stuck with example 2 is there any way i can combine those two, i have something like this Article.objects.filter(**custom_filter) custom filter is dict, for example i have currently custom_filter = { 'app': 1, 'company': 1 } -
Django package to import data from excel file
It's been around 10 months since I am working as a professional Software Engineer (Python). The significance of reusable codes is quite understandable to all of us. We can save lots of each other's time by sharing reusable codes. Frameworks and packages perhaps serve the same purpose. During a project, I had to make a feature where users can upload data from excel files but in a convenient manner. I felt the necessity of using this feature in many projects. Thus, later on, I have made it a package so that anyone can plug it into their project and get benefited. So, if anyone of you requires such a feature, you are welcome to experiment. The package is licensed under MIT and available in pypi. Your contributions to this package will always be appreciated and perhaps, will help other folks. https://github.com/prantoamt/django-parser-app -
Error : The QuerySet value for an exact lookup must be limited to one result using slicing
I am new to django and am creating a question answer app I am getting the following error: The QuerySet value for an exact lookup must be limited to one result using slicing. models.py: from django.db import models from django.contrib.auth.models import User from django.utils.text import slugify from django.contrib.auth.models import User class Log(models.Model): title = models.CharField(blank=False, max_length=500) content = models.TextField(blank=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=50, null=False) created_by = models.CharField(null=True, max_length=500) avatar = models.ImageField( upload_to='images', blank=True) def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.title) super().save(*args, **kwargs) class Meta: verbose_name = ("Log") verbose_name_plural = ("Logs") def __str__(self): return f"{self.title}" class Solutions(models.Model): log = models.ForeignKey( Log, on_delete=models.CASCADE, blank=True, null=True) solution = models.TextField(null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=50, null=False, blank=True) def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.title) super().save(*args, **kwargs) class Meta: verbose_name = ("Solution") verbose_name_plural = ("Solutions") def __str__(self): return f" {self.log.title} {self.solution} " class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) log = models.ForeignKey(Log, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"like by {self.user.username} for {self.log.title}" class Comments(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) log = models.ForeignKey( Solutions, on_delete=models.CASCADE, null=True, blank=True) comment = models.TextField(null=True, blank=True) created_by = models.CharField(null=True, max_length=500) class Meta: verbose_name = ("Comment") verbose_name_plural … -
Can Django Framework be used for API automation testing?
I am supposed to create a python automation framework for API testing (as part of replacing SOAP-UI and we would be using it for Functional/Regression test phases). Can I use Django/Flask for this or these are only meant for development-related stuff? I have come across the simplest way of using "request libraries" incorporated with nosetest/unittest but my client is bit sceptical regarding this and asking me to check for the above "frameworks". Any suggestions would be really helpful. -
Filtering in Django against a JsonField wich is a Json Array with dates values in it
I have a model in Django where there is a JsonField named periodicity which serialize in an Json Array like this: { "id_series": 12381, "country_name": "Central African Republic", "periodicity": [ { "period": "monthly", "start_date": "2010-10-01", "end_date": "2018-10-01" }, { "period": "weekly", "start_date": "2011-10-01", "end_date": "2018-01-01" } ] }, { ... } So my aim is to filter and find the series that have not been updated in less than a certain date. For that I need to query on the end_date of the inner Json Array. What is the best way to do a filtering? I have tried casting the end_date to a date object by doing this : from django.db.models.expressions import RawSQL Serie.objects.annotate(endDate=RawSQL("((periodicity->>'end_date')::date)", [])).filter(endDate__gte=comparisonDate) But so far it has not produced any result. I am looking into something like this https://stackoverflow.com/a/65184218/2219080. -
Sending Mail in django
I am facing a problem when trying to test sending a message from the django app . The problem is that no messages arrive on my email after sending and I don't know what is the reason, please help this is my settings : EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'myname@gmail.com' EMAIL_HOST_PASSWORD = '****************' EMAIL_USE_TLS = True EMAIL_PORT = '587' this is my views.py: def contact_us(requset): subject = requset.POST.get('subject', '') message = requset.POST.get('message', '') from_email = requset.POST.get('from_email', '') send_mail(subject, message, from_email, ['myname@gmail.com']) return render( requset , 'accounts/contact_us.html' ) this is my contact_us.html: <div class="contact_form"> <form name="contact_form" action="" method="POST"> {% csrf_token %} <p><input type="text" name="subject" class="name" placeholder="subject" required></p> <p><textarea name="message" class="message" placeholder="message" required></textare></p> <p><input type="text" name="from_email" class="email" placeholder="email" required></p> <p><input type="submit" value="sent" class="submit_btn"> </p> </form> </div> -
Displaying validation error instead of default text errors in Django UserCreationForm
I have a very simple registration form on my website. My form works, but if a username already exists or my 2 password fields don't match, after I submit the form, Django does not do anything and just focuses the field with the error. I know this is probably an easy fix, but how do I display a validation error if a requirement is not met? For example, if I submit my form with a username that already exists, how do I display an error to the user? My code is down below. Views.py: from django.http.request import RAISE_ERROR from django.shortcuts import render, redirect from django.http import HttpResponse from django.forms import inlineformset_factory from django.contrib.auth.forms import UserCreationForm from .forms import CreateUserForm from django.contrib import messages # from .forms import RegisterForm # Create your views here. def index(request,*args, **kwargs): return render(request, "index.html", {} ) def register(request,): form = CreateUserForm() if request.method == "POST": form = CreateUserForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been successfully created, {username} ') return redirect('login') context = {'form': form} return render(request, "register.html", context ) def login(request,): return render(request,"login.html") Register.html {% load crispy_forms_tags %} {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta … -
I can't get my second django view to validate the post request after the first view redirects
I'm having issue where i want the second view where it validates if a "post" request is validated, execute the set of code. Here's an example: from django.shortcuts import render, redirect from django.http import HttpResponse, Http404 from django.urls import reverse from django.template import loader from django.core.mail import send_mail, mail_admins from .forms import Register # Importing Models from .models import Users # Create your views here. # Create your views here. def register(request): if request.method == "POST": forms = Register(request.POST) if forms.is_valid(): f_name = forms.cleaned_data["first_name"] l_name = forms.cleaned_data["last_name"] em = forms.cleaned_data["email"] num = forms.cleaned_data["phone"] user = Users( first_name=f_name, last_name=l_name, email=em, phone=num ) user.save() request.session['f_name'] = f_name request.session['status'] = True request.session['email'] = em return redirect('success') else: forms = Register() forms = Register() title = "Join now" context = { 'title':title, 'forms':forms, } return render(request, 'register/register.html', context) def success(request): #This part wont validate after the post redirect? **if request.method == 'POST':** welcome = request.session['f_name'] email = request.session['email'] # User Mailing subject = f'Welcome to JSG {welcome}' message = 'Testing' from_email = 'mydev1996@gmail.com' recipient_list = [email] user_mail = send_mail( subject, message, from_email, recipient_list, fail_silently = False, ) # Admin Mailing subject = f'Welcome to JS {welcome}' message = 'Testing' admin_mail = mail_admins( subject, message, … -
Python, django: I don't know how to connect the simple basic fuction I made to the values User put
I did test the basic, simple function on the following and it worked fine. from .area import suburbs print('please select airport direction') e = input() print('please put suburb') b = input() print('please put the number of passengers') c = input() c = int(c) d = suburbs.get(b) d = int(d) def price_cal(self): if e == 'To airport': return d + (c * 10) - 10 elif e == 'From airport': return d + (c * 10) k = int(price_cal()) print(k) Actually User is supposed to select 3 choices To airport / From airport Suburb The number of passengers I would like to calculate the price showing to the webpage (html) with those values User put I tried to write some code at views.py like below but as I exptected, error came out... e = Post.instance.flight_number b = Post.instance.suburb d = suburbs.get(b) d = int(d) c = Post.instance.no_of_passenger c = int(c) class Price: def price_cal(self): if e == 'To airport': return d + (c * 10) - 10 elif e == 'From airport': return d + (c * 10) price_cal() def price_detail(self, request): price = self.price_cal() return render( request, 'basecamp/price_detail.html', { 'price': price, } ) I tried to put instance or object … -
Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add '127.0.0.1' to ALLOWED_HOSTS
I keep on getting this error whenever I run my server locally. This is how allowed hosts is in my .env file ALLOWED_HOSTS=['*'] I have tried adding '127.0.0.1' to the .env file instead of * but nothing seems to be working.Any ideas? -
Why does creating my own custom error pages (400) leads to a Server Error with valid urls?
Hello There, I am trying to create a custom error page (404) in Django. It works well with invalid urls but with valid urls, it gives an error as: Server Error (500) views.py file: def error_404_view(request, exception): return render(request, "400.html") urls.py file, Also this is my Project's urls.py not the app's: handler404 = "members.views.handler404" settings.py file: DEBUG = False ALLOWED_HOSTS = ["*"] Any help will be much appreciated -
How do I set a condition in HTML button tags to stop my Webcam Video Stream on webpage | Python Django
The webcam video stream is displayed on another webpage, so I try to stop my webcam video stream when directed to my homepage but the webcam keeps on running. How can turn it off? here is my views.py still_on = True def gen(tryhaar): while still_on: frame = tryhaar.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') def video_feed(request): return StreamingHttpResponse(gen(VideoCamera()), content_type='multipart/x-mixed-replace; boundary=frame') def home(request): return render(request, "main/home.html",{}) here is my html {% extends 'main/base.html' %} {% block content %} <h1>Stimulus Section</h1> <br> <img src="{% url 'video_feed' %}"> <br> <br> <h2>{{ S6 }}</h2> <br> <br> <br> <button class="btn btn-primary" onclick="location.href='{% url 'home' %}'">Home</button> {% endblock %} My idea is to set a condition in my button tag to let still_on variable to be False when the button is clicked so that the webcam stop running. How can I do that? Or is there other way it can be done? here is my tryhaar.py where VideoCamera class is defined just in case. class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) def __del__(self): self.video.release() def get_frame(self): success, image = self.video.read() raw_img = image.copy() # for dataset gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) eyes_detected = eyes_detection.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5) for (x, y, w, h) in eyes_detected: cv2.rectangle(image, pt1=(x, … -
I could simply delete the migration 0001_initial.py but it is not recommended to delete , so how could I fix this one without deletion of migration
raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration home.0001_initial dependencies reference nonexistent parent node ('cms', '0024_auto_20210516_0955') -
Long loading Django Admin when trying to add Model object
I have really annoying problem with my Django app. It is already deployed to Ubuntu Server, and when I try to access any object of Model called 'Detail', it just won't load the page. The same thing happens when trying to create 'Detail' objects via Django Admin, just infinite downloading. It doesn't happen with other models, though they have the same amount of objects in there (about 181000). It also happened on my local machine before I deployed app to the server, so the problem is not with the server. I guess this happens because of amount of objects in DB table, but there must be some way to fix this problem, so I hope someone can help me with that. -
ajax call not success, the success call back could not be executed
I have used Django2 to develop a web app. I frontend, the ajax call could not work well, the network tab on chrome dev does show the 200 status code, but I did not any alert box. function myFunction() { Swal.fire ({ title: '', text: "Do you want to confirm entries?", type: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes', cancelButtonText: 'No' }).then ( (result) => { if (result.value) { $("#myform").submit(); //sleep(1000); $.ajax ({ url: "{% url 'bms:content_checklist_name_url' %}", type: 'GET', dataType : 'json', success: function(msg_json) { alert(msg_json.responseText) let a = ""; if (a === "Duplicate Entry. This Course Code already exists.") { Swal.fire({ title: '', text: 'Duplicate Entry. This Course Code already exists.', type: 'error', timer: 5000 }) } else { Swal.fire({ title: '', text: 'Entries have been saved.', type: 'success', timer: 5000 }) } }, failure: function(data) { alert('Got an error dude'); } }); } else { window.stop(); } } ) } backend view.py: @csrf_exempt def content_checklist_name_url(request): if request.method == 'POST': ... msg = "success" obj = {"msg": msg} context = {'msg_json': json.dumps(obj)} return render(request, 'bms/main.html',context=context) No error in the console, also not alert shows. the page quickly refreshed without showing any alert message. How could I …