Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django backend cannot access Cookies
Hey I'm trying to access my jwt token in my cookies to do authorization in my backend. But when trying to access my cookie from the request I receive an empty dict. The cookie is created like this in my frontend. cookies.set("jwttoken", result.data.token, { path: "/", maxAge: 3600}); this is done using the universal-cookie npm package. In my backend I try to access my cookies like this. jwt = request.COOKIES.get("jwttoken") But receive None when trying to print the token. This is everything CORS related in my settings.py CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CSRF_USE_SESSIONS = False SESSION_COOKIE_SECURE = False CSRF_COOKIE_SECURE = False CSRF_COOKIE_SAMESITE = None SESSION_COOKIE_SAMESITE = None CORS_ALLOWED_ORIGINS = [ "http://127.0.0.1:8000", "https://********-*******.******.com", "https://www.******.com" ] Thanks for all the help -
Django - How to extend a template from within an app correctly
I am working on a Udemy class to get back into Django development, and this class has me doing the templates folder differently than I am used to. This is the current directory for my file structure showing where my templates are located: VS Code Directory Structure and extended template I can't embed yet, so this is the best I can do. Please ignore the ARCHIVES directory, that is just there while I test things out. I am trying to extend store.html off of base.html, but to test things, I am trying to extend from 'test.html' which you can see in the image. Historically, I have always added the templates directory to the top level, but this class has them on the app level. My problem here is that I can't get the store.html to show up. The test.html (base) is showing up fine, but I can't extend off of it and I have tried messing with the {% extends './test.html' %) as far as using 'store/test.html', 'test.html', and '../test.html'. I know this latter one goes back another directory level, but I just wanted to state that I have been trying to change where it looks. A few things: my … -
Virtual environment not activating in visual studio code windows 11
i am getting this error & : File C:\Users\mudit\vscode\python django projects\dev\venv\Scripts\Activate.ps1 cannot be loaded. The file C:\Users\mudit\vscode\python django projects\dev\venv\Scripts\Activate.ps1 is not digitally signed. You cannot run this script on the current system. For more information about running scripts and setting execution policy, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:3 & "c:/Users/mudit/vscode/python django projects/dev/venv/Scripts/Acti ... + CategoryInfo : SecurityError: (:) [], PSSecurityException + FullyQualifiedErrorId : UnauthorizedAccess check out this screenshot for better understanding. -
Is there a way to test if all my `reverse()` calls in Django Views resolve?
I use reverse('route_name') in my views for redirection. If I do any refactoring of the urls, be it renaming the routes, moving some routes to other urls.py file or something similar, I will have to update all the route names in all my views. It is very easy to miss some of the files. It seems trivial to simply grep all the reverse() calls from all the views and simply check if they resolve. The same thing with template files. It seems trivial to grep all the template names and check if they exist, or have they been moved or renamed and not updated in the views. I'm wondering if there is already some kind of package that does this. I've tried googling, but anything I search for focuses on writing specific tests. I'm wondering if there exists something that will help me avoid writing specific tests for each view. For example: Let's say I have a route: path('/payments/cart', CartView.as_view(), name='payments-cart') If I decide to move the url definition into the payments app, the new name will be cart and the reversing of the url in the view will be done as reverse('payments:cart'). If any of my views still reference … -
Accessing images using URL from a server with restrictions in React
I'm working on a web application using React for the front end and Django for the backend, where I need to display images from a server that has access restrictions in place. These restrictions prevent direct access to the images via a URL(tho I still can access it if I just paste the link into a browser), which is causing issues when trying to display them on my website. Here is an example of the image URL: 'https://mangatx.com/wp-content/uploads/2022/01/Level-1-Player-Manga-Online-193x278.jpg' I've tried using the standard <img> HTML tag to display these images, but I'm encountering a 403 error, indicating that I don't have permission to access the images directly. I have also used a Django templating engine to try to display an image, and it worked somehow, but when I switched to react, it didn't work. Is there a recommended approach or workaround for displaying these images in my web application, considering the server restrictions? I do not want to download the images before displaying them as it will go against the purpose of the application. I also don't want to use a proxy server, as my application has a lot of images and it will be too inefficient. Any ideas would … -
Pytest-django unexpected models test behaviour
I have my Django project with pytest and pytest-django package. I have test_models.py file with my test: import pytest from django.contrib.auth import get_user_model # # Get User model User = get_user_model() # Create your tests here. @pytest.mark.django_db def test_create_user(): assert User.objects.create() I use my custom User model with required fields username, email, password, first_name, last_name. But when I try to create User instance without these fields my tests are passing successfully. Why does my User model have such a behaviour? My models.py: from django.db import models from django.contrib.auth.models import AbstractUser from api.managers import CustomUserManager # Create your models here. # Abstract model TimeStampedModel class TimeStampedModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: # abstract = True to enable models inherit from TimeStampedModel abstract = True # Custom User model class User(AbstractUser, TimeStampedModel): # Make these fields not to be null email = models.EmailField(unique=True, null=False, blank=False) first_name = models.CharField(max_length=30, blank=False, null=False) last_name = models.CharField(max_length=30, blank=False, null=False) # Assing base user manager for admin panel objects = CustomUserManager() I expect that test gives me the error that I can't create a User instance. I've tried to import directly User model from api.models. -
Static files are not loading in Django project in replit
I am working on a project using Python-Django in repl.it. When I set DEBUG=True in settings.py, the static files are loading fine but when DEBUG is set to False (DEBUG=False), the static files are not loading and getting 404 error on the console. Please help me in fixing it. I am assuming there should be a place where we need to define static location like we do in nginx config file as follows location /static/ { alias /var/www/example.com/current/static/; gzip_static on; expires max; add_header Cache-Control public; } Here is my settings.py file: """ Django settings for django_project project. Generated by 'django-admin startproject' using Django 3.2.13. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.getenv('SECRET_KEY') if SECRET_KEY is None: print( "Please setup a SECRET_KEY in the Secrets (Environment variables) tab. See README.md for more." ) exit(1) # SECURITY WARNING: don't run with debug turned on in … -
NoReverseMatch at / Django e python
I'm trying to creat a new app but I am getting this error 'NoReverseMatch at' This is my project urls.py urlpatterns = [ path('', include('app_infos_gerais.urls') ) ] settings.py INSTALLED_APPS = [ 'app_infos_gerais', ] My app urls.py from django.urls import path from . import views app_name= 'app_infos_gerais' urlpatterns = [ path('infosgerais/', views.infos_gerais, name="resultado_infos_gerais") My app view.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def infos_gerais(request): return HttpResponse('Olá, teste!') My app html {% extends 'modelo-tratore.html' %} {% block pagetitle %} Dados gerais {% endblock %} {% load static %} {% block conteudo %} {% if request.user.is_authenticated %} <div> <p>Teste</p> </div> And the file where Im trying to call the url <li class="p-3"> <a href="{% url 'resultado_infos_geraisß' %}">Infos gerais</a> </li> What am I doing wrong? I tried everything I found but nothing worked. -
Не могу выставить правильную временную зону в Django [closed]
Я в самом начале изучения Django. Извиняюсь за глупы вопрос) Создал проект в самом начале не указал временную зону, добавил записи в базу данных и провел миграции. Как правильно исправить временную зону? Чтоб ранее добавленные записи выводились в нужной временной зоне. Пробовал изменить в settings настройку "UTC" на "UTC+6" выдает ошибку. Спасибо. TIME_ZONE = 'UTC' -
celery task received but not executed (eventlet, django)
I faced a problem that when running celery with eventlet and remote database (Redis) tasks come but are not executed, before that I used gevent and it worked correctly with both local and remote databases, but it does not have the ability to stop tasks, I tried all the options I found on the Internet and on StackOverflow, but none of them helped. I add my settings there Django settings: # settings.py CELERY_BROKER_URL = REDIS_CONN_URL + "0" CELERY_RESULT_BACKEND = REDIS_CONN_URL + "0" CELERY_WORKER_CONCURRENCY = 1000 Celery settings: import os import ssl from celery import Celery from celery.schedules import crontab os.environ.setdefault("DJANGO_SETTINGS_MODULE", "SailAPI.settings") celery_app = Celery( "SailAPI", broker_use_ssl={"ssl_cert_reqs": ssl.CERT_REQUIRED, "ssl_ca_certs": ssl.get_default_verify_paths().cafile}, redis_backend_use_ssl={"ssl_cert_reqs": ssl.CERT_REQUIRED, "ssl_ca_certs": ssl.get_default_verify_paths().cafile}, ) celery_app.config_from_object("django.conf:settings", namespace="CELERY") celery_app.conf.update( enable_utc=True, timezone="UTC", worker_concurrency=8, worker_pool="eventlet", ) celery_app.conf.beat_schedule = { "update_user_status": { "task": "user_app.tasks.update_user_status", "schedule": crontab(hour="4", minute="0", day_of_week="sat"), } } celery_app.autodiscover_tasks() The problem is that tasks that are added to the queue are not executed. I use an eventlet (because it has the ability to stop tasks that are running) and when I run it locally (Windows) with a local database (redis) it works fine, accepts tasks, executes them, stops at the command, but when I threw the code on the server (Linux) and ran … -
text are going out of the container and it's appearing in just one line and goes out of the page
I am trying to add some texts to my project-details section using rich text uploading field in Django admin. There it should be in a paragraph as I have added them in my Django admin project description but it's showing a line and also it goes out of the container and, but it gives space on the left side of the container but not in the right side of container and it goes out of page 😥 here is my project-details.html page: {% extends "base.html" %} {% load static %} {% static "images" as baseUrl %} {% block title %}{{projectdetails.title}}{% endblock %} <!--header block --> {% block header %} <!-- Slider Start --> <section class="section about"> <div class="container">{{projectdetails.desc|safe}}</div> </section> <!--slider ends --> <!-- footer Start --> {% block footer %} <!--Essential Scripts --> {% block Scripts %} {% endblock %} {% endblock %} {% endblock %} here is my project.html page: {% extends "base.html" %} {% load static %} {% static "images" as baseUrl %} {% block title %}Project{% endblock %} <!--header block --> {% block header %} <!-- slider starts --> </div> <div class="typing"> <p class="type4"></p> </div> <!-- section portfolio start --> <section class="section box"> <div class="container"> <div class="row … -
Why is my form calling the wrong Django view?
The flow of my app is as follows: A file is submitted on the transcribe.html page first which then redirects to the transcibe-complete.html page where the user can click to beginning transcription. Why is the 'transcribeSubmit' view being called instead of the 'initiate_transcription' view when the user clicks the 'click to transcribe' button on the 'initiate_transcription' page? Each page has their own JS file to ensure that forms are submitted separately. html: (transcribe.html): <form method="post" action="{% url 'transcribeSubmit' %}" enctype="multipart/form-data" > {% csrf_token %} <label for="transcribe-file" class="transcribe-file-label">Choose audio/video file</label> <input id="transcribe-file" name="file" type="file" accept="audio/*, video/*" hidden> <button class="upload" id="transcribe-submit" type="submit" >Submit</button> </form> (transcribe-complete): <form method="post" action="{% url 'initiate_transcription' %}" enctype="multipart/form-data"> {% csrf_token %} <label for="output-lang--select-summary"></label> <select class="output-lang-select" id="output-lang--select-summary" name="audio_language"> <option value="detect">Detect language</option> <option value="zh">Chinese</option> <option value="en">English</option> <option value="es">Spanish</option> <option value="de">German</option> <option value="jp">Japanese</option> <option value="ko">Korean</option> <option value="ru">Russian</option> <option value="pt">Portugese</option> </select> </div> <div class="transcribe-output"> <button id="transcribe-button" type="submit">Click to Transcribe</button> </div> </form> JS: const form = document.querySelector('form'); form.addeventlistener('submit', function (event) { event.preventdefault(); const formdata = new formdata(form); const xhr = new xmlhttprequest(); xhr.open('post', form.getattribute('action'), true); xhr.onreadystatechange = function () { console.log("ready state: ", xhr.readystate); console.log("status: ", xhr.status); } xhr.responsetype = 'blob'; xhr.send(formdata); }); views.py: @csrf_protect def transcribeSubmit(request): if request.method == 'POST': form = … -
Render the Django REST Framework uploading system with an HTML script
I have developed a simple file-upload system using Django REST Framework using this tutorial How to upload files to AWS S3 with Django. Basically the system allows user to upload files to an AWS S3 bucket. This is what the users currently see: This is the following django project structure: DROPBOXER-MASTER | |--- dropboxer | |--- settings.py |--- urls.py |--- wsgi.py |--- uploader | |--- views.py |--- urls.py |--- serializers.py |--- models.py |--- apps.py |--- templates |--- index.html |--- manage.py |--- requirements.txt This is the dropboxer/urls.py: from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include # new urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('rest_framework.urls')), # new path('', include('uploader.urls')), # new ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) This is the dropboxer/settings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*****************************************' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["*"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', … -
ERROR [internal] load metadata for docker.io/library/python:3.9-alpine3.13
I'm new to docker, trying to build a website by following a online course but i was struck with this error in the beginning itself FROM python:3.9-alpine3.13 LABEL maintainer="rohitgajula" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /tmp/requirements.txt COPY ./app /app WORKDIR /app EXPOSE 8000 RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ /py/bin/pip install -r /tmp/requirements.txt && \ rm -rf /tmp && \ adduser \ --disabled-password \ --no-create-home \ django-user ENV PATH="/py/bin:$PATH" USER django-user Error is [+] Building 1.3s (4/4) FINISHED docker:desktop-linux => [internal] load .dockerignore 0.0s => => transferring context: 191B 0.0s => [internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 492B 0.0s => ERROR [internal] load metadata for docker.io/library/python:3.9-alpine3.13 1.3s => [auth] library/python:pull token for registry-1.docker.io 0.0s ------ > [internal] load metadata for docker.io/library/python:3.9-alpine3.13: ------ Dockerfile:1 -------------------- 1 | >>> FROM python:3.9-alpine3.13 2 | LABEL maintainer="rohitgajula" This is the error i'm getting i dont understand whats the error here. -
Django html href query last object pass id to url tag
I have a button in my base template that needs to direct to a form to edit the last object in my model. model: class Cast(models.Model): id = models.AutoField(db_column='Id') startdate = models.DateTimeField(db_column='StartDate') enddate = models.DateTimeField(db_column='EndDate') View: def castend(request, id): context ={} obj = get_object_or_404(Cast, id = id) form = EndCastForm(request.POST or None, instance = obj) if request.method == 'POST': cast=Cast.objects.last() if form.is_valid(): form.save() cast.refresh_from_db() cast.endcastcal() cast.save() return HttpResponseRedirect("/wwdb/casts/%i/castenddetail" % cast.pk) context["form"] = form return render(request, "wwdb/casts/castend.html", context) url path('casts/<id>/castend/', views.castend, name='castend'), base.py This if/else statement determines if the enddate field is populated, the Start Cast button is passed to the view. Else the End Cast button is passed to the view. The End Cast button requires an id argument passed to the url. <div class="top-button-container stickey-top"> {% if cast.objects.last.enddate %} <button type="button" class="btn btn-danger btn-lg btn-block"> <a class="nav-link" href="{% url 'caststart' %}">Start Cast</a> </button> {% else %} <button type="button" class="btn btn-danger btn-lg btn-block"> <a class="nav-link" href="{% url 'castend' %}">End Cast</a> </button> {% endif %} </div> Start cast form This form is how the user inputs most of the information for an entry. Once the form is submitted, the view redirects to the endcast form, using the cast object to pass … -
Best practice to set user to admin
I am currently thinking what would be the best procedure to set a user to admin on a webapp after they have subscribed. Briefly for information: On this website users can sign up for subscriptions that give them admin rights. The payment is done via PayPal. After users have paid successfully the backend (in my case Django) receives the Paypal webhook with all necessary information about which user should be set to admin. This works so far. Afterwards a confirmation mail is sent out automatically. The problem with the whole thing is that the authprovider in the frontend pulls information like the user role from the JWT tokens. When the access token is updated with the refresh token, it gets the information like user role from the refresh token (at least that's how it's handled in Django). This means that if users have subscribed to be admins, they already are according to the database, this information reaches the frontend only when you log out and then log in again. This doesn't seem to me to be the best solution. Also problematic is that the PayPal webhook takes a few seconds longer to arrive in my backend. That is, after purchase … -
is MERN is better then Django for remote jobs and for joining startups?
I am a university student and I have been working on Django projects from 8-9 months, and I have made like 7 projects and 1 is in progress for practicing and mastering Django, But one of my senior said to me, that getting Django remote jobs & freelancing is relative hard compare MERN stack so should switch to MERN stack? to get clarity so that I choose a right path. -
Send actual email to real recipient when developing Django app
I just wanna know if there is any way to send emails to someone, like my own email, in development in order to test the style and everything. Is there anything built-in in Django or any free SMTP service out there to help me with that? REMEMBER: I wanna get the email in my inbox not in console. -
Is it possible to split HTML view and Python back-end across different servers (IIS) in Django?
I have a Django application where I want to separate the HTML views and the Python back-end logic into two different servers for architectural and security reasons. Specifically, I want one server to handle all the HTML rendering and another server to handle the Python back-end logic like database queries, API calls, etc. Is it possible to do this while still leveraging Django's capabilities? If so, how can I achieve this split? If it is not doable, may you explain why ? Thank you in advance for your help. -
NoReverseMatch on Django URL when more than one present
I have a table with a list of data values on it. One of the columns contains a link to another page. Sometimes there could be one link, sometimes two and sometimes n. When there is only one link present the code works as expected, the pattern matches and it goes to the expected page. Whenever there is more than one link present it fails. It will still build the url correctly, I can see the full correct url in my search bar on my browser but I get a NoReverseMatch error. Error: Exception Type: NoReverseMatch Exception Value: Reverse for 'thelink' with arguments '('64f75fake8012b456073fake', '')' not found. 1 pattern(s) tried: ['thelink/(?P<table>[^/]+)/(?P<row>[^/]+)\\Z'] urls.py path('thelink/<str:table>/<str:row>', views.thelink, name='thelink'), html where it works and breaks: <td> {% for table, row in data %} <a href="{% url 'thelink' table row %}" type="button" class="badge badge-info"> link </a>&nbsp; {% endfor %} </td> Generated HTML from the html code: Working: <a href="/thelink/64f75fake8012b456073fake/64f75be82fakeb456073fake" type="button" class="badge badge-info">link</a> Not Working: <a href="/thelink/64f75fake8012b456073fake/64f75be82fakeb45603fake1" type="button" class="badge badge-info">link</a> <a href="/thelink/64f75fake8012b456073fake/64f75be82fakeb45603fake2" type="button" class="badge badge-info">link</a> <a href="/thelink/64f75fake8012b456073fake/64f75be82fakeb45603fake3" type="button" class="badge badge-info">link</a> Note: I did alter the ids and links but you can assume those are correct. I have also tried looking at these solution(s): sol1, sol2 -
Django form in template
I was trying to build a form that make the user able to upload a picture from the website to Media\Images folder. i try this but it dosent work models.py from django.db import models # Create your models here. class imgUpscalling(models.Model): Image = models.ImageField(upload_to='images/') forms.py from django import forms from .models import imgUpscalling class ImageForm(forms.ModelForm): class Meta: model = imgUpscalling fields = ('Image',) views.py def img_upscaler(request): context = {'from': ImageForm()} return render(request, "upsc_main.html",context) template.html <h1>Image Upscaler & Enhanced Resolution</h1> <h2>Select the Image</h2> <form method = "post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> can you notify me with the mistakes i did in the code? because the form is not shown in the template. thanks a lot in advance -
How do I properly set PYTHONPATH when invoking the Django Python shell?
I'm using Python 3.9.9 for a Django 3 project. I would like to invoke my Python shell, via "python3 manage.py shell", so I have set these variables ... $ echo $PYTHONSTARTUP /home/myuser/cbapp/shell_startup.py $ echo $PYTHONPATH/myuser /home/myuser/cbapp/ My startup script is very simple ... $ cat /home/myuser/cbapp/shell_startup.py from cbapp.services import * from cbapp.models import * However, when I change to my project directory, activate my virtual environment, and attempt to invoke the shell, I get these errors complaining about not being able to find Django ... $ cd /home/myuser/cbapp $ ./venv/bin/activate $ python3 manage.py shell Traceback (most recent call last): File "/home/myuser/cbapp/manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/myuser/cbapp/manage.py", line 21, in <module> main() File "/home/myuser/cbapp/manage.py", line 12, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? However, Django has already been installed in my virtual environment ... $ ls /home/myuser/cbapp/venv/lib/python3.9/site-packages/django/ apps conf core dispatch http __main__.py __pycache__ template test utils bin contrib db forms __init__.py middleware shortcuts.py … -
Sending Audio file from Django to Vue
I'm trying to send gtts generated audio file from Django to Vue via HttpResponse. Django's views.py: f = open('path/of/mp3/file', 'rb') response = HttpResponse() response.write(f.read()) response['Content-Type'] = 'audio/mp3' response['Content-Length'] = os.path.getsize('path/of/mp3/file') return response and when vue receives the response data, it is like the below: data: '��D�\x00\x11C\x19�\x01F(\x00\x00\x04 �&N�""""���ޓ�������\x7F���B\x10���w�����…���_�F��1B��H���\x16LAME3.100�����������������������' # and so on I guess it is because the bytes have been converted to string over the transfer and I have to convert it back to the audio file. But no matter whether using blob or other suggested methods, I could not convert it to an mp3 file to be played in javascript. How could I achieve this? -
how to fix django login problems
I was working on django project but I could not login into my django app after successful registration(confirmed from admin side). I have added phone number field to registration page, help me fix the login code, i am new to programming help me out please my code looks like this: This is my view.py ````def register_view(request): """Registration view.""" if request.method == 'GET': # executed to render the registration page register_form = UserCreationForm() return render(request, 'netflix/register.html', locals()) else: # executed on registration form submission register_form = UserCreationForm(request.POST) if register_form.is_valid(): User.objects.create( first_name=request.POST.get('firstname'), last_name=request.POST.get('lastname'), email=request.POST.get('email'), phone=request.POST.get('phone'), username=request.POST.get('email'), password=make_password(request.POST.get('password')) ) return HttpResponseRedirect('/login') return render(request, 'netflix/register.html', locals()) def login_view(request): #Login view. if request.method == 'GET': # executed to render the login page login_form = LoginForm() return render(request, 'netflix/login.html', locals()) else: # get user credentials input username = request.POST['email'] password = request.POST['password'] # If the email provided by user exists and match the # password he provided, then we authenticate him. user = authenticate(username=username, password=password) if user is not None: # if the credentials are good, we login the user login(request, user) # then we redirect him to home page return HttpResponseRedirect('/logged_in') # if the credentials are wrong, we redirect him to login and let him … -
How to check Fullcalendar V5 Refetch Events Success / Failure
I was fetching events from the server dynamically for fullcalendar var calendar = new FullCalendar.Calendar(document.getElementById('calendar'), { themeSystem: "bootstrap5", businessHours: false, initialView: "dayGridMonth", editable: true, headerToolbar: { left: "title", center: "dayGridMonth,timeGridWeek,timeGridDay", right: "today prev,next", }, events: { url: '/api/lesson_plans/', method: 'GET', success: function () { eventsLoadSuccess = true; }, failure: function () { eventsLoadSuccess = false; notyf.error('There was an error while fetching plans.'); }, textColor: 'black' }, dateClick: function(plan) { var clickedDate = plan.date; var today = new Date(); // Today's date if (clickedDate >= today) { $('#addPlanModal input[name="start"]').val(moment(clickedDate.toISOString()).format('YYYY-MM-DD HH:mm:ss')); $('#addPlanModal').modal('show'); } }, eventClick: function (plan) { $.ajax({ method: 'GET', data: { plan_id: plan.event.id }, success: function(data) { if (data.form_html) { $('#ediPlanFormContainer').empty(); $('#ediPlanFormContainer').html(data.form_html); $('#editPlanForm #plan_id').val(plan.event.id); initDatePicker(["id_edit_start", "id_edit_end"]); $('#editPlanmodal').modal('show'); } else { notyf.error('Error While Fetching Plan Edit Form.'); console.error('No form HTML found in the response.'); } }, error: function(xhr, textStatus, errorThrown) { console.error('Error:', textStatus, errorThrown); } }); }, eventDrop: function(plan) { updateEvent(plan.event); }, }); calendar.render(); It works properly but on reload events I wanted to check if the reload was successful or not but the refetchevents function doesn't return anything so I was trying to implement my own way but I am stuck now I need some help. $('#reload_plans').click(function () { if …