Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any way to keep tasks running on server side in django?
Basically i have a bot in my django webapp when given your social media credentials it manages your one of social media accounts i was able to succesfully run it while the client is still on website and as you would expect it stopped when the client closed the website. Is there any way to store the credentials and then keep the bot running even after user leaves website and so that bot still manages the account? The bot is mostly making few requests and API calls. Thank You -
Is it better to make custom registration with editing Django UserCreationForm class or make it on a new table and class?
I wanted to make a Django authentication but I was confused about wichone is better? is it is better to edit the venv/Lib/site-packages/django/contrib/auth/forms.py file and make my custom form and edit DB on venv/Lib/site-packages/django/contrib/auth/models.py or it's better to make my authentication system with model and views and forms on my application? -
django.core.exceptions.FieldError: Cannot resolve keyword 'duration' into field when trying to select a property field
there are alot of questions on this particular error but none caused by trying to select a property field from the serializer, below are my code # seriliazer.py class ProjectActivitySerializer(serializers.ModelSerializer): is_running = serializers.ReadOnlyField() duration = serializers.ReadOnlyField() # i am trying to select this particular field to perform some calculation class Meta: model = ProjectActivity fields = '__all__' class GetTotalProjectActivityTime(ListAPIView): """ """ serializer_class = ProjectActivitySerializer permission_classes = (IsAuthenticated, IsOwner|IsAdminUser) # protect the endpoint def get_queryset(self): return ProjectActivity.objects.filter(user=self.kwargs['user'], project__id=self.kwargs['project']).values('duration') Just a background to my problem here: i have the below response [ { "id": 1, "is_running": true, "duration": "2 days, 5:43:26", "description": "worked on developing dashboard endpoint", "start_time": "2021-12-22T11:40:49.452935Z", "end_time": null, "project": 1, "user": 1 } ] I want to run a calculation on the duration but the duration field isn't part of my model field but a just property. now i am finding it difficult to run the caculation -
I am stuck with this problem when I trying to do
when I am going to try this error arises def showsaleF(request): sobj=Sale.objects.all() ob=Sale.objects.values_list('Customer_id') customername=Customer2.objects.raw('SELECT Customer_Name FROM customer_table WHER id=%s',[ob]) productobj=Product.objects.all() mylist = zip(sobj,customername,productobj) return render(request, 'showsale.html',{'sobj':mylist}) ProgrammingError at /showsale (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'id='<QuerySet [(1,), (1,), (1,), (2,)]>'' at line 1") -
can I use like django signals functions in node.js
when the user registers, a new object is added to the user model, at which time a new object must be added to the profile model, the user and profile models are linked. With Django’s signal pack, this thing was pretty easy but I can’t do it on node.js -
How can I Style the forms in Django?
Hello fellow developers, I am struggling to style forms in Django. I have tried it once somewhat 3 to 4 months that time it worked but this time it's not working I am not sure that I doing it the correct way. I want to style the above form to look like the below form. new_sales.html(Working one) {% load static %} {% load crispy_forms_tags %} {% load widget_tweaks %} <!DOCTYPE html> <html> <head> <title>Sales | New</title> <link rel="stylesheet" href="{% static 'resoures/css/style.css' %}"> <link rel="stylesheet" href="{% static 'vendors/css/1.3 grid.css.css' %}"> <link rel="stylesheet" href="{% static 'vendors/css/ionicons.min.css' %}"> <link rel="stylesheet" href="{% static 'vendors/css/hint.css' %}"> <link rel="stylesheet" href="{% static 'vendors/css/normalize.css' %}"> <link href="https://unpkg.com/ionicons@4.5.10-0/dist/css/ionicons.min.css" rel="stylesheet"> </head> <body> <nav> <div class="nav_box--img-box"> <img src="{% static 'resoures/img/Me.jpg' %}" alt="Owner Image"> </div> <div class="nav_box--heading-box"> <h1>Harishree Chemist</h1> <h3>Medical Retailer</h3> </div> <div class="nav_box--menu-box"> <a href="#"><span class="ion-ios-search"></span> Search</a> <a href="{% url 'purchase' %}"><span class="ion-ios-log-in"></span> Purchase</a> <a href="{% url 'Sales' %}" style="border-left: 5px solid var(--light-blue); background-color: hsl(194, 100%, 95%);"><span class="ion-ios-log-out"></span> Sales > <span class="ion-md-add-circle-outline"></span> Add New Bill</a> <a href="{% url 'Stocks' %}"><span class="ion-ios-cube"></span> In Stock</a> <a href="#"><span class="ion-ios-analytics"></span> Analytics</a> </div> <div class="nav_box--user-box"> <a href="#">Log out</a> </div> </nav> <main> <div class="first-box"> <div class="row"> <div class="col span-3-of-9"> </div> <div class="col span-3-of-9"> <h1 class="heading" style="text-align:center">Add New … -
Heroku release fails, error related to django.utils
So I updated my python code to Django 4.0 and with that, had to remove and update some deprecated code as "ungettext_lazy" and similar. Locally, the code is compiling well but when I push it to heroku, I get this error: from django.utils.translation import ungettext_lazy ImportError: cannot import name 'ungettext_lazy' from 'django.utils.translation' (/app/.heroku/python/lib/python3.9/site-packages/django/utils/translation/__init__.py) I've tried a few things but haven't been able to update this on heroku. -
Django rest framework ListApiView slow query
I have a displays table with 147 rows. I am not doing any heavy computation on this data set I just need to get it fast from the database. For now, the load time is 3-4 seconds. Other data comes really fast, why? Does the ListApiView work slow? @permission_classes([AllowAny]) class DisplaysList(generics.ListAPIView): queryset = Displays.objects.all() serializer_class = serializers.DisplaySerializer -
How to resolve an error after deploy on heroku?
After deploy I have an error whenever I try to push a button. What to do? Text of error: ProgrammingError at /notion/ relation "base_notion" does not exist LINE 1: ... "base_notion"."title", "base_notion"."body" FROM "base_noti... -
How to connect redis heroku for websocket?
I'm making chat. I need to deploy my django app to heroku. I did it via the docker. I use free heroku redis and django-channels. Redis cancels my connection and I'm getting ConnectionResetError: [Errno 104] Connection reset by peer In settings i have CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get("REDIS_URI")], }, }, } And my REDIS_URI I got from heroku-resources-heroku_redis-settings consumers.py 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 print('==================================') print('==================================') print(self.room_name) print(self.room_group_name) print('==================================') print('==================================') await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() .................... And the traceback 2021-12-24T15:59:15.190002+00:00 heroku[router]: at=info method=GET path="/ws/chat/FIRST/?access=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjQwMzY1MDY5LCJpYXQiOjE2NDAzNTQyNjksImp0aSI6ImZiNTg2N2MzNzg4NzRiN2M4NmJjNzM1YTJmNmQ1MTFmIiwidXNlcl9pZCI6MX0.JPPRPZAWE0iJ9BqBXYNZLc27u_CNqX90zX9F6MMJpf4" host=ggaekappdocker.herokuapp.com request_id=47782ca1-01c4-42e5-a589-5502869d2393 fwd="178.121.19.23" dyno=web.1 connect=0ms service=569ms status=500 bytes=38 protocol=https 2021-12-24T15:59:14.973191+00:00 app[web.1]: 2021-12-24 15:59:14,972 INFO ================================== 2021-12-24T15:59:14.973292+00:00 app[web.1]: 2021-12-24 15:59:14,973 INFO ================================== 2021-12-24T15:59:14.973402+00:00 app[web.1]: 2021-12-24 15:59:14,973 INFO FIRST 2021-12-24T15:59:14.973507+00:00 app[web.1]: 2021-12-24 15:59:14,973 INFO chat_FIRST 2021-12-24T15:59:14.973604+00:00 app[web.1]: 2021-12-24 15:59:14,973 INFO ================================== 2021-12-24T15:59:14.973719+00:00 app[web.1]: 2021-12-24 15:59:14,973 INFO ================================== 2021-12-24T15:59:14.974246+00:00 app[web.1]: 2021-12-24 15:59:14,974 DEBUG Creating tcp connection to ('ec2-34-241-115-34.eu-west-1.compute.amazonaws.com', 29080) 2021-12-24T15:59:14.975178+00:00 app[web.1]: 2021-12-24 15:59:14,975 DEBUG Creating tcp connection to ('ec2-34-241-115-34.eu-west-1.compute.amazonaws.com', 29080) 2021-12-24T15:59:14.979031+00:00 app[web.1]: 2021-12-24 15:59:14,978 DEBUG Cancelling waiter (<Future pending cb=[<TaskWakeupMethWrapper object at 0x7f3c21189c40>()]>, [None, None]) 2021-12-24T15:59:14.979466+00:00 app[web.1]: 2021-12-24 15:59:14,979 DEBUG Closed 0 connection(s) 2021-12-24T15:59:14.979729+00:00 app[web.1]: 2021-12-24 15:59:14,979 DEBUG Cancelling waiter (<Future cancelled>, [None, … -
cannot upload HTML image to a website, however local file URL works fine
before you say that it's a duplicate, please read the entire thing. I have the following piece of code: <title>the-doge.net</title> <!-- add the image--> <img src="doge-poster1.png" height="500" width="800" style="display: block; margin-left: auto; margin-right: auto;"/> <body style="background-color:black;"> <!--add the login and register buttons--> <input type="image" src="register.png" style="display:inline; position:absolute; top:50px; right: 7%;"/> <input type="image" src="login.png" style="display:inline; position:absolute; top:50px; left: 12%;"/> </body> however, it says Not Found: /login.png Not Found: /doge-poster1.png Not Found: /register.png I have looked at various answers on Stack Overflow, including this, and also a few websites like here and provided full directory, and a image on img.bb, but it all did not work. Here is my file structure: ... landing(folder) --migrations (folder) --templates (folder) ----landing (folder) ------base.html ------doge-poster1.png ------index.html ------login.png ------navbar.html ------register.png note: In PyCharm there is a way to open a local file URL and it works fine, but python manage.py runserver doesn't seem to display any of the images. -
How to hash strings in python(django) and compare the hashed value with a given string
I'm working on a web app that allows users to sign up then login, I used the following functions to hash the password from passlib.hash import pbkdf2_sha256 import math def encrypt_password(pswd): encrypt_pswd = pbkdf2_sha256.encrypt(pswd, rounds=(int(math.pow(len(pswd),3))), salt_size=(len(pswd)*2)) return encrypt_pswd def verify_password(pswd, e_pswd): en_pswd = encrypt_password(pswd) if en_pswd == e_pswd: return True else: return False my problem is that the string I hashed doesn't produce the same result when I hash it for a second time. How can I resolve this issue or what methods can I use hash the password, store in the database and compare that value with the one from the login form -
Apache + mod_wsgi + Django + dataclasses stopped working after upgrade to python3.10
After upgrading to python3.10 code with dataclasses stopped working with mod_wsgi. If a class is created with @dataclass decorator (with just a single attribute x: str) and then instantiated somewhere in apps.py at module level, an exception is thrown. The reason is missing generated __init__ method (I confirmed that everything works if I define __init__ manually). Unfortunately, in real project it's part of external library and dataclass is instantiated in imported module, so there's no way to define __init__ by hands. The code without changes (all packages have same versions too) works with python3.9. To be clear, here's the code: # models.py from dataclasses import dataclass @dataclass class Test: foo: str # apps.py from django.apps import AppConfig from .models import Test Test('bar') # Error is thrown here class AppConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'app' It seems like there's a bug somewhere. I also know that mod_wsgi only support python up to 3.8, according to data on pypi, but can't believe the answer is "Look for other wsgi solution or don't upgrade yet" (if so - tell me too, it might be true). You might notice that Django is of version 3.2 in requirements while 4.0 is available: I tried … -
Django Wrong File Path / Redirect and Pass Data
I am struggling to get this right. I am trying to redirect from PageOne to PageTwo and while supplying PageTwo with selected data from PageOne. I have tried a few things and can't seem to get this right. Method 1 Changing File Path class PageOne(TemplateView): template_name = 'home/pageone.html' def get(self, request): args = {} return render(request, self.template_name, args) def post(self, request, *args, **kwargs): if request.POST.get('confirm'): name = request.POST.get('hidden_get_client_name') data= request.POST.get('get_data') args = {'name':name,'data':data} new_template_name = 'home/PageTwo.html' return render(request, new_template_name, args) This works, but the file path is still /PageOne when the page loads. How do I change this to PageTwo? Method 2 Redirect response = redirect('/PageTwo/') return response Using this method, the file path is correct, but I am unable to pass data? Any help would be greatly appreciated. I am struggling to effectively redirect between pages while passing data. -
Django new project ModuleNotFoundError: No module named 'demoapp' (virtual env's name)
I am trying to start a new Django project but running into the error ModuleNotFoundError: No module named '<XYZ>' where XYZ is the name of my virtual environment created using mkvirtualenv. This is really weird and I can't say what has changed in my system recently to cause this. Here are steps showing how this error occurs in a brand new project: Create the virtual environment: ~/code/projects/temp$ mkvirtualenv demoapp created virtual environment CPython3.9.6.final.0-64 in 237ms creator CPython3Posix(dest=/Users/ankush/.virtualenvs/demoapp, clear=False, no_vcs_ignore=False, global=False) seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/Users/ankush/Library/Application Support/virtualenv) added seed packages: pip==20.3.3, setuptools==51.3.3, wheel==0.36.2 activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator virtualenvwrapper.user_scripts creating /Users/ankush/.virtualenvs/demoapp/bin/predeactivate virtualenvwrapper.user_scripts creating /Users/ankush/.virtualenvs/demoapp/bin/postdeactivate virtualenvwrapper.user_scripts creating /Users/ankush/.virtualenvs/demoapp/bin/preactivate virtualenvwrapper.user_scripts creating /Users/ankush/.virtualenvs/demoapp/bin/postactivate virtualenvwrapper.user_scripts creating /Users/ankush/.virtualenvs/demoapp/bin/get_env_details Install Django: (demoapp) ~/code/projects/temp$ pip install django Collecting django Using cached Django-4.0-py3-none-any.whl (8.0 MB) Collecting asgiref<4,>=3.4.1 Using cached asgiref-3.4.1-py3-none-any.whl (25 kB) Collecting sqlparse>=0.2.2 Using cached sqlparse-0.4.2-py3-none-any.whl (42 kB) Installing collected packages: sqlparse, asgiref, django Successfully installed asgiref-3.4.1 django-4.0 sqlparse-0.4.2 WARNING: You are using pip version 20.3.3; however, version 21.3.1 is available. You should consider upgrading via the '/Users/ankush/.virtualenvs/demoapp/bin/python -m pip install --upgrade pip' command. Start a new project (demoapp) ~/code/projects/temp$ django-admin startproject uberclone Run the new project right away: (demoapp) ~/code/projects/temp$ cd uberclone/ (demoapp) ~/code/projects/temp/uberclone$ ./manage.py runserver Traceback (most … -
Django testing CSV response
i'm writing a simple app whose job is to scrape data from some api, add data to database, and finally load this data and generate CSV file. Its main funcionality is working, but i have to write unit tests, and I have no idea what should I focus on. This is my main function which task is to call another function that scrape and save data to database, and then it generate CSV file. def csv_output(request): api_get_data() response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=users_tasks.csv' writer = csv.writer(response) writer.writerow(['User name', 'City', 'Task title', 'Task boolean']) for task in Task.objects.all().order_by('user_id'): user = User.objects.get(id=task.user_id) writer.writerow([user.full_name, user.address.city, task.title, task.completed]) return response This is function that scrapes data from api, and saves it in database. def api_get_data(): user_response = get_data_from_url('users') if user_response: for item in user_response: obj_user, created_user = User.objects.update_or_create( id=int(item.get('id')), defaults={ 'full_name': item.get('name'), 'username': item.get('username'), 'email': item.get('email'), 'phone_number': item.get('phone'), 'website': item.get('website') } ) addr_items = item.get('address') obj_address, created_address = Address.objects.update_or_create( user=obj_user, defaults={ 'street': addr_items.get('street'), 'suite': addr_items.get('suite'), 'city': addr_items.get('city'), 'zipcode': addr_items.get('zipcode') } ) task_response = get_data_from_url('todos') if task_response: for item in task_response: task_obj, task_created = Task.objects.update_or_create( user_id=item.get('userId'), id=item.get('id'), defaults={ 'id': item.get('id'), 'title': item.get('title'), 'completed': item.get('completed') } ) My question is, what should i focus on? … -
"You need to enable JavaScript to run this app"; response is html instead of json
Technologies used: Django, Djoser, react.js, webpack I made the request in react.js: const config = { headers: { "Content-Type": "application/json", }, }; const body = JSON.stringify({ email, first_name, last_name, password, re_password, }); const response = await axios.post( `http://127.0.0.1:8000/auth/users/`, body, config ) I used Djoser in the backend to handle the auth requests. I console.log the response and find that the response is html instead of JSON. The status is 200 but it should be HTTP_201_CREATED based on Djoser's documentation. I checked that Djoser is in INSTALLED_APPS in Django and I have djoser==2.1.0. I try to add "proxy": "http://127.0.0.1:8000", in package.json, not working. I also try to use fetch instead of axios, also not working. I am not sure where the problem comes from. -
How to populate second drop down by using the selection of first drop down in django?
I have tree dropdowns ! Lets say Drop1, Drop2, Drop3. Now each populates data's from database. Now my problem is as below. I need to somehome populate the Drop2 data based on Drop1 and Drop3 data based on Drop2. Lets say if user selects Drop1 - Option A //selected By using this Option A i need to filter and fetch data for Drop2 Drop2 - Option A2 // fetched based on Drop1 Selection And same applies to Drop3 How to handle this ? I have populated the data for Drop1, but confused on how to select for Drop2 based on Drop1. Please guide Thank you. I dont know what code to share, so please let me know if you guys need anything -
TypeError at /mark_your_attendance Can't parse 'center'. Sequence item with index 0 has a wrong type
enter image description here i am trying to run this project but its giving TypeError at /mark_your_attendance Can't parse 'center'. Sequence item with index 0 has a wrong type Project Github Link: https://github.com/prathmachowksey/Attendance-System-Face-Recognition -
TypeError at /register/ list indices must be integers or slices, not str
How can i solve this issue in my forms.py from django import forms from django.forms.widgets import EmailInput, FileInput, PasswordInput, TextInput, Textarea from django.contrib.auth.models import User from django.contrib.auth import authenticate,get_user_model User = get_user_model() class RegistertionForm(forms.Form): first_name = forms.CharField(widget=TextInput(attrs={ 'class': 'validate form-control', 'placeholder': 'Full Name', 'type': 'text', 'id': 'first_name'}), min_length=2, max_length=150) username = forms.CharField(widget=TextInput(attrs={'class': 'validate form-control', 'placeholder': 'Username', 'type': 'text', 'id': 'username'}), min_length=4, max_length=150) email = forms.CharField(widget=EmailInput(attrs={'class': 'validate form-control', 'type': 'email', 'placeholder': 'Enter your email address', 'id': 'email'})) number = forms.CharField(widget=TextInput(attrs={'class': 'validate form-control', 'type': 'number', 'placeholder': 'phone number', 'id': 'number'})) password = forms.CharField(widget=PasswordInput(attrs={'class': 'validate form-control', 'type': 'password', 'placeholder': 'Password', 'id': 'password'})) password2 = forms.CharField(widget=PasswordInput(attrs={'class': 'validate form-control', 'type': 'password', 'placeholder': 'Confirm-password', 'id': 'password2'})) description = forms.CharField(widget=Textarea(attrs={'class': 'validate form-control', 'placeholder': 'Write about yourself', 'id': 'description'})) # picture = forms.CharField(widget=FileInput(attrs={'class': 'validate form-control', 'type': 'file', 'id': 'profile', 'name': 'profile'})) def clean_firstname(self): firstname = self.cleaned_data['firstname'].lower() qs = User.objects.filter(firstname=firstname) if qs.count(): raise forms.ValidationError("Name already exists") return firstname def clean_username(self): username = self.cleaned_data['username'].lower() qp = User.objects.filter(username=username) if qp.count(): raise forms.ValidationError("Username already exist") return username def clean_email(self): email = self.cleaned_data['email'].lower() r = User.objects.filter(email=email) if r.count(): raise forms.ValidationError("Email already exists") return email def clean_phone(self): number = self.cleaned_data['email'].lower() r = User.objects.filter(number=number) if r.count(): raise forms.ValidationError("Phone number already exists") return number def clean_password2(self): … -
Make API call on page load (Django)
I'm trying to figure out a way to make an API call and retrieve the results on page load. Any pointers would be appreciated! -
Why am i getting server 500 error in Django?
I have been trying to use the Django template inheritance feature for my project Since I've added {% block content %}s I am now getting a server error 500 whenever I try to run the child template. The base template runs fine. I am quite sure it has something to do with the content blocks, but I'm not sure why as I don't repeat any names of blocks and everything on the child template is contained within a block. Code goes like this: Base.html <!DOCTYPE html> <style> 'My style' </style> <html lang='en'> <head> <meta charset='UTF-8' {% block title %} webpage {% endblock %} <script>'Jquery reference'</script> </head> {% block script %} 'empty' {% endblock %} <body> <div id='navbar'> 'My navbar' </div> <div id='main_content_block'> {% block content %} <h1>This is my base</h1> {% endblock %} </div> </body> </html> Home.html {% extends 'main/base.html' %} {% block title %} <title>Home</title> {% endblock %} {% block script %} 'My javascript' {% endblock %} {% block content %} 'My content' {% endblock %} Thanks for your time -
How to deploy django app with channels and websocket to Heroku?
I'm creating messanger. I met a need to deploy my app to heroku. My config/settings.py from pathlib import Path from datetime import timedelta import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = True ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_simplejwt', 'corsheaders', 'users', 'tokens', 'channels', 'chat', 'college' ] AUTH_USER_MODEL = 'users.User' ASGI_APPLICATION = 'config.asgi.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [(os.environ.get('REDIS_URI'), 25690)], }, }, } TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'config.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('ELEPHANT_NAME'), 'USER': os.environ.get('ELEPHANT_USER'), 'PASSWORD': os.environ.get('ELEPHANT_PASSWORD'), 'HOST': os.environ.get('ELEPHANT_HOST'), 'PORT': 5432 } } STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') ........................ I user heroku-redis config.asgi import os from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import chat.routing from config.middlewares import TokenAuthMiddleware os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": TokenAuthMiddleware( URLRouter( chat.routing.websocket_urlpatterns ) ), }) Procfile release: python manage.py migrate web: daphne config.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python manage.py runworker channels --settings=core.settings -v2 Honestly I don't know which port i should specify. Don't … -
Heroku Serving Localhost URL (127.0.0.1:8000) in Ajax API URLs in Django App
I'm currently working on a Django project and it's hosted on Heroku from GitHub. The front-end is served via Ajax calls to an API. let myurl = "/api/properties/"; $.ajax({ async: true, url:myurl, method:'GET', success: function(result){ .... } }); Everything works well on localhost, but on Heroku, I keep getting the error: GET http://127.0.0.1:8000/api/properties/ net::ERR_CONNECTION_REFUSED My API URL has no http://127.0.0.1:8000 on GitHub but on Heroku it has it after analyzing the source code on the Sources tab on Chrome: let myurl = "http://127.0.0.1:8000/api/properties/"; $.ajax({ async: true, url:myurl, method:'GET', success: function(result){ .... } }); I don't understand why my app's API URL isn't taking the domain URL https://appname.herokuapp.com/api/properties/ and it's across all the Ajax API URLs on the Django app. I have cleared my browser cache, opened the app in 'incognito mode' and even redeployed the project several times but not change. Kindly help me debug this and understand where the localhost URL is coming from. -
Django 3.2.8: 0 static files copied to '/static'
This error occurs when performing command python manage.py collectstatic: 0 static files copied to '/home/project'. That means there is no changes and my static files already exist in the destination but in this folder only one file: static/ - staticfiles.json But I want all my CSS, js, HTML for panel admin to be in it. Django Settings: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "/static/") STATICFILES_DIRS = ( STATIC_ROOT, ) urls.py ... urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) I also tried these 1, 2 but no results were found.