Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Starting a login session once check_password verifies a password is correct
I have a user logi form i am using to authenticate users in django and this is the code that processes from django.contrib.auth.hashers import make_password from django.contrib.auth.hashers import check_password from django.contrib.auth import login def process_login(request): if request.method == 'POST': var = request.POST["email_or_telephone"] print(var) obj=AuthUsers.objects.create( email_address = "info@google.com", user_type = "inapp", telephone_number = "08002556155", user_password = make_password("logan2900"), account_status = "not_verified", full_names = "Michael Jackson", pronouns = "Hee/Hee", country = "UK", gps_location = "London", role_name = "user", profile_picture = "image.png", kyc_documents = "1.png,2.jpg" ) obj.save() if check_password("logan2900", "pbkdf2_sha256$320000$S8u10Fh1yz0NssYphC1qW1$LvnhBHACIqr6dGX7Bae19k8/yGf/omNLQcvl88QXodv="): print("Correct Password") else: print("Incorrect Password") I am using the the check_password method to check if a user password is correct and the function works as expected. How can i start session and actually login user after verifying the password is correct? Also after successfully logging the user, how can i verify a user is logged in in another function? -
Django: how to check if the users that are registered under me have new users registered under them in Django
I am writing a referral system logic in django. The referral system works fine now, but what i want to implement is this. When i refer a user "user 2" and "user 3", it is stored that i have refered two users, now how do i check if "user 2" or "user 3" which are refered by me: have gotten a new user refered by them ("user 2" or "user 3"). This is the code i have written to register users as referalls views.py def registerRef(request, *args, **kwargs): profile_id = request.session.get('ref_profile') print('profile_id', profile_id) code = str(kwargs.get('ref_code')) try: profile = Profile.objects.get(code=code) request.session['ref_profile'] = profile.id print('Referer Profile:', profile.id) except: pass print("Session Expiry Date:" + str(request.session.get_expiry_age())) form = UserRegisterForm(request.POST or None) if form.is_valid(): if profile_id is not None: recommended_by_profile = Profile.objects.get(id=profile_id) ref_earn = InvestmentPackageID.objects.get() instance = form.save() registered_user = User.objects.get(id=instance.id) registered_profile = Profile.objects.get(user=registered_user) registered_profile.recommended_by = recommended_by_profile.user registered_profile.save() else: instance = form.save() registered_user = User.objects.get(id=instance.id) profile = Profile.objects.get(user=registered_user) profile.save() username = form.cleaned_data.get('email') password = form.cleaned_data.get('password1') user = authenticate(username=username, password=password) login(request, user) return redirect('core:index') context = {'form':form} return render(request, 'userauths/sign-up.html', context) in the profile model i have a field like this models.py class Profile(models.Model): ... code = models.CharField(max_lenght=100, ...) recommended_by = models.ForeignKey(User, ...) What is β¦ -
Grouping entries from PostgreSQL database by their week or month based on timestamp value?
I have been trying to resolve a solution to this for a while now but due to my inexperience with both postgres(and SQL in general) and Django ORM I haven't been able to get a result that I can use. I have this model: class EventItem(models.Model): Id = models.CharField(max_length=200, primary_key=True) StartTime = models.DateTimeField(null=True) EndTime = models.DateTimeField(null=True) Duration = models.TimeField(null=True) Creator = models.CharField(max_length=50, null=True) and I want to get the EventItems and group the entries by their week and/or month. So for every week starting from the earliest entry group all of the events for that week into one group. Right now I am able to return the week number for each individual item by doing this: weeks = EventItem.objects.annotate(week=ExtractWeek('StartTime')).values('week') But this obviously doesn't group the results and I also need to keep the columns from the original table. -
Django authenticate() command returns None
I am doing a website which has Google sign in and I am trying to log in the user when they click the sign in with Google button. This is the code that doesn't work: def google_login(request): security_key = request.GET.get("security_key","") email = request.GET.get("email","") if security_key == "" or email == "": return redirect("/403/") timestamp_now = time.time() try: obj = GoogleSignupToLoginSecurityKey.objects.get(email=email,security_key=security_key) if (timestamp_now-float(obj.timestamp_created)) < 50: print(email) user = authenticate(email=email, password="GOOGLE USER") print(user) if user is not None: login(request, user) else: redirect_url = "/accounts/signup/" return redirect(redirect_url+"?error=google_unknown") return redirect("/accounts/signup/welcome/") else: return redirect("/accounts/signup?error=google_unknown") except: return redirect("/403/") return All the security and timestamp stuff is for security purposes but the bit that doesn't work is the authenticate() command. For this command the email is retrieved by a url parameter and I have checked and it is correct. For a Google Account I have made the password "GOOGLE USER" since I am lazy and haven't bothered taking out the password field for a Google Account, this means that every Google account has the same password but for this type of account it is completely unnessesary to have a password. The command returns "None". Hopefully you understand this and I haven't made it too confusing. -
TypeError at /password-reset/ filter_users_by_email() got an unexpected keyword argument 'is_active'
I am trying to use the password-reset api endpoint in dj_rest_auth. It requires that I enter the email address of the user but wehenever I do that, I get TypeError at /password-reset/ filter_users_by_email() got an unexpected keyword argument 'is_active' error. Please help me solve this. Thank you. models.py from django.conf import settings User = settings.AUTH_USER_MODEL from django.contrib.auth.models import AbstractUser from django.db import models from django.contrib.auth.models import UserManager from orders.models import Orders # Create your models here. class CustomUser(AbstractUser): phone_number = models.CharField(max_length=100) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) id = models.IntegerField(primary_key=True) username = models.CharField(max_length=100, default="") email = models.CharField(max_length=100, default="") def save(self, *args, **kwargs): self.id = self.user.id self.username = self.user.username self.email = self.user.email super().save(*args, **kwargs) def __str__(self): return f'{self.user.username} Profile' urls.py from django.contrib import admin from django.urls import path, include from orders import views from django.views.generic import TemplateView from dj_rest_auth.views import PasswordResetView, PasswordResetConfirmView urlpatterns = [ path('admin/', admin.site.urls), path('', TemplateView.as_view(template_name='index.html')), path(('users/'), include('users.urls')), path('orders-list/', views.OrdersList, name = "orders-list"), path('orders-detail/<str:pk>', views.OrdersDetail, name = "orders-detail"), path('orders-create/', views.OrdersCreate, name = "orders-create"), path('orders-update/<str:pk>', views.OrdersUpdate, name = "orders-update"), path('orders-delete/<str:pk>/', views.OrdersDelete, name = "orders-delete"), path('password-reset/', PasswordResetView.as_view()), path('password-reset-confirm/<uidb64>/<token>/', PasswordResetConfirmView.as_view(), name = 'password_reset_confirm'), path("djangoflutterwave/", include("djangoflutterwave.urls", namespace="djangoflutterwave")) ] -
DJango project & app layout and Imports seem to be extremely repetative
I'm trying to layout my Django app, and I just cannot figure out what the appropriate way to do it is. I've read many questions and blog posts, but nothing seems obvious. Here's my app (I hate the repetition of these terms like buildhealth, but I guess it's idomatic in Django?) - the name of the project, created by django-admin startproject buildhealth and the name of the first app (a performance dashboard) created by django-admin startapp performance is performance): [ROOT] βββ ... βββ buildhealth β βββ __init__.py β βββ buildhealth β β βββ __init__.py β β βββ asgi.py β β βββ performance β β β βββ __init__.py β β β βββ ... β β β βββ views.py β β β βββ ... β β βββ settings.py β β βββ urls.py β β βββ wsgi.py β βββ ... β βββ manage.py β βββ staticfiles β βββ ... βββ poetry.lock βββ pyproject.toml βββ ... This sort of works, but then i have files all over the place for doing imports which feels terrible. For example - in settings.py, i have to type this: ROOT_URLCONF = "buildhealth.buildhealth.urls" This feels super wrong to have two imports like this. Am I laying this out wrong? β¦ -
Django Limit Choices in Admin
I need to filter categories that I can select in PostAdmin exact which was confirmed, how to do that? in models: class Category(models.Model): name = models.CharField(max_length=200) confirmed = models.BooleanField(default=False) .... def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=255) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category') ... def __str__(self): return self.title in admin: class PostAdmin(models.ModelAdmin): list_display = ['title', 'category'] fields = ['title, 'category'] admin.site.register(Post, PostAdmin) -
Create django query that would give results like this [{"modelfield3_value": {"modelfield1": "value1", "modelfield2": "value2"} }]
How can I create django query that would give results like this [{"modelfield3_value": {"modelfield1": "value1", "modelfield2": "value2"} }]? Basically, the {"modelfield1": "value1", "modelfield2": "value2"} part is the dictionary that .values() method returns. Is such thing possible with django orm and postgres or I need to use the python for this? -
How to count the number of a nested array in django?
I am new to django and I'm still figuring out how use all the functions. This is the result of the query that I want to count { "id": 1, "user_id": 1, "encountersDaily": [ { "id": 1, "DateTime": "2022-08-01T01:22:00Z", "Longtitude": "14.536480570700000", "Latitude": "121.049722723900000", "EncounterExitID": 1, "PromoterID": 1, "GenderID": 1 }, { "id": 10, "DateTime": "2022-08-01T01:42:46Z", "Longtitude": "14.536480570700000", "Latitude": "121.049722723900000", "EncounterExitID": 1, "PromoterID": 1, "GenderID": 1 } ], }, { "id": 4, "user_id": 4, "encountersDaily": [ { "id": 6, "DateTime": "2022-08-01T01:42:09Z", "Longtitude": "14.536480570700000", "Latitude": "121.049722723900000", "EncounterExitID": 2, "PromoterID": 4, "GenderID": 1 }, { "id": 8, "DateTime": "2022-08-01T01:42:29Z", "Longtitude": "14.536480570700000", "Latitude": "121.049722723900000", "EncounterExitID": 1, "PromoterID": 4, "GenderID": 1 }, { "id": 9, "DateTime": "2022-08-01T01:42:38Z", "Longtitude": "14.536480570700000", "Latitude": "121.049722723900000", "EncounterExitID": 1, "PromoterID": 4, "GenderID": 2 } ], } I have this data of 2 users and my goal is to loop through this array and find the sum of the encountersDaily. is it possible to just use filter function here? or loop is necessary . -
Trying to load static images from JS script in Django
I am using a 'select2' dropdown 'https://select2.org/dropdown' component in Django to display a dropdown menu that has a flag image next to each item. In development I was creating a string literal in my JS code to point to the static img folder , but now I've deployed the application to AWS and my static files are being served through an S3 bucket and now the image is not loading. select2 component js code: function formatState (state) { if (!state.id) { return state.text; } var baseUrl = "static/img/flags"; var $state = $( '<span><img src="' + baseUrl + '/' + state.element.value.slice(0,3).toLowerCase() + '.png" class="img-flag" /> ' + state.text + '</span>' ); return $state; }; in my html inspector the image source produces: img src="static/img/flags/bsd.png" class="img-flag"> I can obviously see that the img src above is not pointing to my s3 bucket, so I've tried to create a string literal for a static img inside of the select2 js code to reproduce {% static '/img/flags/all.png' %} : '<span><img src="' + '{% static' + '"' + '/' + 'img' + '/' + 'flags' + '/' + state.element.value.slice(0,3).toLowerCase() + '.png' + '"' + ' %}' + 'class="img-flag" /> ' + state.text + '</span>' this β¦ -
assert celery task runs or not runs
I am working on a django project as an Intern, I am developing the project not coding it from start, I added a feature to contact us section, the feature is about sending support's answer to user who sent the contact message via email after the support answered the message in admin panel, I start celery task for sending email in post_save receiver function based on some conditions, I would like to unit test this feature, what is matter to me is does celery receives task in some conditions or it doesn't I need something like this assertCeleryRecievesTask(task_name) or not, for now it is not important if the task itself works as expected just wanna know if the task starts or not, thanks for your help. -
redirect to detail view after authentication in django templates
I have a simple Group model: class Group(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=55) description = models.TextField() joined = models.ManyToManyField(User, blank=True) With a simple GroupDetail template: <div>Leader: {{group.leader}}</div> <div>Name: {{group.name}}</div> <div>Description: {{group.description}}</div> {% if user.is_authenticated %} <form action="{% url 'join_group' group.pk %}" method="POST"> {% csrf_token %} <button type="submit" name="group_id" value="{{group.id}}">JOIN</button> </form> {% else %} <div><a href="{% url 'login' %}">Login</a> to join chaburah</div> {% endif %} The idea is that if a User is authenticated (signed in) they can join a group. My issue is that right now, when a User clicks login they're redirected to the login page, but after login they don't return to Group they were about to join. Is there a way to sort of stash the url they were at return to it after authentication? This is becoming more important as I add invite links and private groups, where a User is sent a link to join a private Group that isn't displayed on the home page (using {% if group.private != True %} so the User won't be able to return to the Group detail without having to reclick the link they were sent. -
trouble with testing advisory_lock with pytest
Im currently trying to test a function that will lock some string and will not allow to do anything under that locked string, using advisory_lock. so here is my code: import pytest from django_pglocks import advisory_lock from threading import Thread from time import sleep def function_that_should_lock(): with advisory_lock('secret_string', wait=True): sleep(10) @eager_db_test def test_archive_qualifications_from_project_resource_lock(): failed = False lock_project_resource_qa_action_thread = Thread( target=function_that_should_lock, ) lock_project_resource_qa_action_thread.start() with advisory_lock(f'secret_string', wait=False): failed = True assert not failed For some reason function_that_should_lock actually doesn't lock the string, and failed will be set to True. Please help me understand how it works =) -
cant get selenium to work i want to test my django channels application
im trying to test my app and even if i do the most basic things my selenium refuses to work all i get is a long error message and i cant figure out why im new to selenium and i cant understand these errors, would love some help, im working on static server in django idk if its important CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } tests.py import time from channels.testing import ChannelsLiveServerTestCase from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait class ChatTests(ChannelsLiveServerTestCase): @classmethod def setUpClass(cls): try: super().setUpClass() cls.driver = webdriver.Chrome('C:\\Users\\David\\Desktop\\VSProjects\\LiveChat\\chromedriver.exe') cls.driver.implicitly_wait(10) except: cls.tearDownClass() @classmethod def tearDownClass(cls): cls.driver.quit() super().tearDownClass() def test_admin_login(self): self.driver.get(self.live_server_url) time.sleep(20) error code (livechat_env) PS C:\Users\David\Desktop\VSProjects\LiveChat\livechatapp> py manage.py test --keepdb Found 1 test(s). Using existing test database for alias 'default'... System check identified no issues (0 silenced). DevTools listening on ws://127.0.0.1:53585/devtools/browser/326e028a-0c32-4557-93a4-6c55304bae1d ETraceback (most recent call last): File "<string>", line 1, in <module> File "C:\Python310\lib\multiprocessing\spawn.py", line 107, in spawn_main new_handle = reduction.duplicate(pipe_handle, File "C:\Python310\lib\multiprocessing\reduction.py", line 79, in duplicate return _winapi.DuplicateHandle( OSError: [WinError 6] The handle is invalid ====================================================================== ERROR: test_admin_login (room.tests.ChatTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\David\Desktop\VSProjects\LiveChat\livechat_env\lib\site-packages\django\test\testcases.py", line 287, in _setup_and_call self._pre_setup() File "C:\Users\David\Desktop\VSProjects\LiveChat\livechat_env\lib\site-packages\channels\testing\live.py", line 52, in β¦ -
cannot show the field 'name' in REST API
When I try to retrieve all data from my REST API I get them correctly except from one field, that is the field 'name' from Skill class. Instead of the 'name' I get only its id. Can you help me to resolve this?---------------------------------------------- here is the output Here is the code: models.py from django.db import models from django.forms import ImageField from django.utils.text import slugify class Skill(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Project(models.Model): title = models.CharField(max_length=200) sub_title = models.CharField(max_length=200, null=True, blank=True) front_page = models.ImageField(null=True, blank=True, upload_to="images", default="broken-image.png") body = models.TextField(null=True, blank=True) created = models.DateTimeField(auto_now_add=True) skills = models.ManyToManyField(Skill, null=True) slug = models.SlugField(null=True, blank=True) def __str__(self): return self.title def save(self, *args, **kwargs): if self.slug == None: slug = slugify(self.title) has_slug = Project.objects.filter(slug=slug).exists() count = 1 while has_slug: count += 1 slug = slugify(self.title) + '-' + str(count) has_slug = Project.objects.filter(slug=slug).exists() self.slug = slug super().save(*args, **kwargs) serializers.py from rest_framework import serializers from project.models import Project, Skill class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = '__all__' views.py from rest_framework.response import Response from rest_framework.decorators import api_view from project.models import Project, Skill from .serializers import ProjectSerializer from rest_framework import status from django.shortcuts import get_object_or_404 @api_view(['GET']) def getData(request): project = Project.objects.all() serializer = ProjectSerializer(project, β¦ -
Django for APIs: Build web APIs with Python and Django
I am currently searching for Django for APIs: Build web APIs with Python and Django 4.0 PDF it would be very helpful if anyone provide me with this books pdf -
unsupported operand type(s) for *=: 'dict' and 'int' - Django RowNumber()
I'm trying to use RowNumber() : qs = self.filter_queryset(self.get_queryset()) qs = qs.annotate( row_number = Window( expression = RowNumber(), order_by = F('score').desc() )) order_by part returns the error: unsupported operand type(s) for *=: 'dict' and 'int' How can I fix? -
omiting path from url
I'm newbie in Django Channels and I'm trying to follow and recreate this project from Django channels documentation (which is 4 part) : https://channels.readthedocs.io/en/latest/tutorial/part_1.html#add-the-index-view as you can see for accessing the project I have to go with STH like this: 192.168.43.175:8000/chat/lobby_room I'm wondering how to completely omit the path and accessing the project through : 192.168.43.175:8000/ This is my urls.py : from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('chat/', include('chat.urls')), ] This is my views.py : from django.shortcuts import render # Create your views here. def index(request): return render(request, 'chat/index.html') def room(request, room_name): return render(request, 'chat/room.html', { 'room_name': room_name }) This is my chat application urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<str:room_name>/', views.room, name='room'), ] This is my routing.py: from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()), ] This is my consumers.py: import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from β¦ -
email verification via apppassword is not working
In my Django e-commerce project i was using my g mail account as EMAIL_HOST_USER for sending email verification for registering.but since may30 2022 the less secure apps feature has been disabled.and i got error when i tray to signup with new email .and to let 3rd party apps access gmail I generate an App password for my e-commerce in my gamil account and i change EMAIL_HOST_PASSWORD from my gamil password to the new generated apppassword and when i tray to signup,the error is gone but still it dose not send activation link to the new email !so how can I fix this issue ? -
Cannot satisfy path requirement for an image in FilePathField of model and display it in a template
As per a tutorial I have a model with: class Project(models.Model): ... image = models.FilePathField(path="/img") The files are rendered in the template with: {% extends "base.html" %} {% load static %} ... <img class="card-img-top" src="{% static project.image %}"> ... {% endblock %} In the tutorial, the image files were entered manually and it all worked because they were stored in app_name/static/img. But when I try to enter a new Project via the admin it cannot find the /img directory. But if I change the path= to an absolute address such as /home/me/project_name/app__name/static/img as apparently necessary, or even /static/img, which seems to be accepted, the template adds an extra 'static'in front of the address. I could remove the 'load static' from the template, but I wonder whether there is a better way. Also I am not sure how all this fits into the use of 'collectstatic' later on for production servers. -
django_cities_light not populate No module named 'myapp.settings" I use cookie cutter
I've just create a new project : pubsauvage with cookie cutter django. I want to use Django-cities-light (last version). So I add module and do migrate. I can see all the tables cities_light (empty). When I want to populate with manage.py cities_light I have this error: Thaks for help to solve this. ModuleNotFoundError: No module named 'pubsauvage.settings' -
In Django views.py I create a session in method A and try to read it in class B. Error: attribute session not defined in class B
this may have a straigthforward solution. I hope you can help me. I have the following @api_view(['POST']) def methodA(request): myvariable=request.data['list'] # This is an Ajax Post request.session['myvar'] = myvariable print(request.session['myvar']) # it works. shows Ajax Post value return JsonResponse({'success':True}) class classB(classC): def myvarmethod(request): print(request.session['myvar']) def importantmethod(self): self.myvarmethod() ... return [...] # some stuff My goal is to print 'request.session['myvar']' inside classB (in importantmethod()). The output is: object myChart has not attribute session. Where do I need to define session? -
Validation Check Not Working in Form.py Django
I have to create this validation rule when Start= (start_new + start_old) >0 or is positive and End = (end_new + end_old) >0 or is positive then the validation error will raise that" Positive Strat and Positive End are not allowed in the conjunction", But with my below code it is not checking the validation rule and allowing the positive start and positive end values in the conjunction. **When I debugged the code the the end_new and end_old values are not storing thats why the validation not working any idea how i can solve this error ** my code in django form.py for i in range(count): start_new = int(self.data.get(f'applicationruntime_set-{i}-start_new') or 0) start_old = int(self.data.get(f'applicationruntime_set-{i}-start_old') or 0) end_new = int(self.data.get(f'applicationruntime_set-{i}-end_new') or 0) end_old = int(self.data.get(f'applicationruntime_set-{i}-end_old') or 0) if (start_new + start_old) > 0 and (end_new+end_old) > 0: raise ValidationError( f" Positive Start values and Positive End values are not allowed to be used in conjunction") -
Is there a way could deploy Django project on namecheap in ASGI mode?
I'm trying to deploy my Django on Namecheap, the server should work but I got the following message traceback: [ERROR] [UID:12123][2655752] wsgiAppHandler pApp->start_response() return NULL. Traceback (most recent call last): File "/home/alshigpf/website/passenger_wsgi.py", line 41, in __call__ return self.app(environ, start_response) TypeError: __call__() missing 1 required positional argument: 'send' [ERROR] [UID:12123][2655752] wsgiAppHandler pApp->start_response() return NULL. Traceback (most recent call last): File "/home/alshigpf/website/passenger_wsgi.py", line 41, in __call__ return self.app(environ, start_response) TypeError: __call__() missing 1 required positional argument: 'send' This is what my passenger_wsgi.py file looks like: import os import sys import django sys.path.append(os.getcwd()) os.environ['DJANGO_SETTINGS_MODULE'] = 'website.settings.development' django.setup() SCRIPT_NAME = os.getcwd() print("Script name: ", SCRIPT_NAME) class PassengerPathInfoFix(object): """ Sets PATH_INFO from REQUEST_URI because Passenger doesn't provide it. """ def __init__(self, app): self.app = app print("Start Init") print("App is: ", self.app) print("End Init") def __call__(self, environ, start_response): from urllib.parse import unquote print("Start Calling") environ['SCRIPT_NAME'] = SCRIPT_NAME request_uri = unquote(environ['REQUEST_URI']) script_name = unquote(environ.get('SCRIPT_NAME', '')) offset = request_uri.startswith(script_name) and len(environ['SCRIPT_NAME']) or 0 environ['PATH_INFO'] = request_uri[offset:].split('?', 1)[0] return self.app(environ, start_response) # Get ASGI application from website.routing import application print("Before calling application") application = PassengerPathInfoFix(application) when I googled I glanced that there's something called "Uvicorn" which is an updated version of Gunicorn to handle ASGI mode. when I did β¦ -
when I call this javascript function in django template like this "<h4 id="followings" onclick="followings();">followings</h4>" it is not working
when I call this javascript function(stored in static files) in django template like this "followings" it is not working. But other functions are working. javascript caode function followings() { let url = 'following/' console.log(url) fetch(url) .then(response => response.json()) .then(data => { var body = document.getElementById('follow-body') body.innerHTML = null for (let x = 0; x < data.length; x++) { var user = `<div class="recom-user"> <img src="${data[x].profile_pic}" alt=""> <div class="recom-user-name"> <p class="username">${data[x].full_name}</p> <p class="userid">${data[x].user}</p> </div> <button class="follow-btn">unfollow</button> </div>` b ody.innerHTML += user } }) } i called it like this: <h4 id="followings" onclick="followings();">followings</h4>