Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best solution to integrate independent applications into a Django (& React) platform?
I have a general platform that I want to evolve. The platform is hosted on a domain like "https://www.example.com". For certain specific users, I would like to give them access to a completely independent application (several applications, independent platform) from their profile on a subdomain like "https://subdomain.example.com". I would like these applications to have: Their own database Be accessible only for authenticated and authorized users Their own server The Django project of the general platform is written in Django/React. Before launching this project, I am wondering about the best way to integrate these independent applications into the main platform. I have done some research and manipulation, but I don't know how to decide on the project architecture: django-host, django-tenant, django-site ... Below is my current architecture What is the best possible option to connect other independent applications to the general platform with the current users? -
Django ignores timezone settings
I am trying to create a record in my Django project with the timezone set to Europe/Rome. When I create the model object, I use this function to set the timezone: MyModel.objects.create( name="trial", date=datetime_aware("2023-08-15") ) However, I am encountering an issue where the record is being stored with the date "2023-08-14" and the UTC timezone (GMT), despite my efforts to set it to Europe/Rome. In order to do this, I first set the following values in my settings.py file: USE_TZ = True TIME_ZONE = "Europe/Rome" Next, I wrote a function to create a datetime object with the appropriate timezone: def datetime_aware(dt_string, timezone=settings.TIME_ZONE): if dt_string: dt = datetime.datetime.strptime(dt_string, "%Y-%m-%d") dt_aware = make_aware(dt, pytz.timezone(timezone)) return dt_aware return None Can you help me figure out what's going wrong? -
How to make the updated_by field display the user's full name in Django?
I just recently started using Django. Please help me figure it out. I have a database that stores various information about network devices. On the site, this information is displayed in a table. I want the updated_by field to display the full name of the user who created this table or who last modified it. All users are registered in Django, there are fields: first name, last name. I want these two fields to be displayed together in the table in the updated_by field. For example, at the end of the table on the site it was written: Updated by an employee: Ivanov Ivan. I tried to do this: from django.contrib.auth.models import User updated_by = models.ForeignKey(User, verbose_name='Updated by an employee', on_delete=models.SET_DEFAULT, default='Employee deleted') But I am getting an error OperationalError at /admin/mainapp/device/1/change/ no such column: device.updated_by_id -
simple_settings.LazySettings raises "cannot import name 'get_cache' from 'django.core.cache'"
The following import fails only on my github actions workflow, but works on my local env: from simple_settings import LazySettings /opt/hostedtoolcache/Python/3.10.11/x64/lib/python3.10/site-packages/simple_settings/__init__.py:1: in <module> from .models import Settings /opt/hostedtoolcache/Python/3.10.11/x64/lib/python3.10/site-packages/simple_settings/models.py:2: in <module> from django.core.cache import get_cache E ImportError: cannot import name 'get_cache' from 'django.core.cache' (/opt/hostedtoolcache/Python/3.10.11/x64/lib/python3.10/site-packages/django/core/cache/__init__.py) Has anyone else encoutered this? Here's the requirements also: certifi==2022.12.7 chromedriver_autoinstaller==0.4.0 django_simple_settings==0.3.1 jira==3.4.1 openapi_core==0.16.5 pytest==7.2.0 pytest_schema==0.1.1 python_dateutil==2.8.2 PyYAML==6.0 requests==2.28.1 selenium==4.8.2 simple_settings==1.2.0 six==1.16.0 urllib3==1.26.13 Python 3.10, OS: Ubuntu-latest -
Each child in a list should have a unique "key" prop error in django + react app
I've tried everything, React keeps giving me the same error: "Each child in a list should have a unique "key" prop." It's a django project with a react app inside, i'm building a form where i want the users to select a category from a dropdown. models.py: class Category(models.Model): title = models.CharField(max_length=20) slug = models.SlugField() def __str__(self): return self.title api.py @permission_classes((AllowAny,)) class CategoriesView(APIView): def get(self, request, *args, **kwargs): categories = Category.objects.all() serializer = CategorySerializer(categories, many=True) return Response(serializer.data) categories_view = CategoriesView.as_view() serializers.py: class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('title',) dropdown v1: <label htmlFor="categories">Categories</label> <select id="categories" value={categoryID} onChange={(event) => setCategoryID(event.target.value)} > <option key="default" value=""> Select category: </option> {categories && categories.filter(category => category).map((category) => ( <option key={category.id} value={category.id}> {category.title} </option> ))} </select> dropdown v2: <select id="categories" value={categoryID} onChange={(event) => setCategoryID(event.target.value)} > <option key="default" value="">Select category:</option> {categories && categories.filter(category => category).map((category) => ( <option key={uuidv4()} value={category.id}> {category.title} </option> ))} </select> data fetching: const [categories, setCategories] = useState([]); const [categoryID, setCategoryID] = useState(''); useEffect(() => { const fetchCategories = async () => { const response = await fetch('/api/categories/'); const data = await response.json(); if (Array.isArray(data)) { setCategories(data); } else { console.error('Data returned from API is not an array:', data); } }; fetchCategories(); … -
How to get region of user in loggs Django
I'm looking for way to get info about which region user from and add that in logg file I already can have their ip with function def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return str(ip) And then i add that into logg info def writing_logs(request, action): logger.info('{} {} {} {}'.format( request.user.email, get_client_ip(request), action)) And i want to know how to do something like that and show country/region/city of request user -
Django Admin page Glitch
Recently, in the last two projects the home page of the admin url in django appears with the following css glitch. enter image description here As I have done everything in the same way as the previous project I don't know why this is happening. Is this a recent bug with the newer versions? enter image description here Here is my settings.py: from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] CORS_ALLOWED_ORIGINS = [ "http://127.0.0.1:5173", ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # External 'rest_framework', 'corsheaders', # Internal Apps 'todo', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', "corsheaders.middleware.CorsMiddleware", 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = "backend.urls" 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 = "backend.wsgi.application" # Database DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3", } } … -
How can I create Bulk message sender site like SendGrid?
I am trying to create bulk mail sender website like SendGrid. But I am confused how can I create without using any API of plugins I create my own API so please help me. If anyone know How it will done. I am trying to create website like SendGrid. -
Django ModuleNotFoundError, project cannot recognize my application
when i use 'python manage.py runserver' ModuleNotFoundError is come.. project cannot recognize my application 'main' i ask it to chatGPT and modify insert 'main' in settings.py but project still cannot recognize 'main' -
Aggrgate JSON key value of JSONField Django PostgreSQL
I have a simple model setup as below, import random import string from django.db import models def random_default(): random_str = "".join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10)) return {"random": random_str, "total_price": random.randint(1, 100)} class Foo(models.Model): cart = models.JSONField(default=random_default) I want to get the sum of total_price from all Foo instances. In native Python, I can do something like below to get the sum, but I believe it is suboptimal. sum(foo.cart["total_price"] for foo in Foo.objects.all()) I tried the following aggregate queries with Django, but none seems correct/working. 1. Foo.objects.aggregate(total=models.Sum(Cast('cart__total_price', output_field=models.IntegerField()))) # Error # django.db.utils.DataError: cannot cast jsonb object to type integer 2. Foo.objects.aggregate(total=models.Sum('cart__total_price', output_field=models.IntegerField())) # Error # django.db.utils.ProgrammingError: function sum(jsonb) does not exist # LINE 1: SELECT SUM("core_foo"."cart") AS "total" FROM "core_foo" ^ # HINT: No function matches the given name and argument types. You might need to add explicit type casts. Question What is the proper/best way to get the sum of top-level JSON keys of a JSONField? Versions Python 3.8 Django 3.1.X -
Trouble printing context in Django Cookiecutter template
Background: Django Cookiecutter template psql db Have created a new app and installed it per settings.py file What I want = data from db to flow into the template view Problem: No matter what I try I can't get the data visible in the template view on my local host. Views.py file ('<projectslug>/<projectslug>/appname/views.py) from django.shortcuts import render def exercise_table(request): var_dict = { 'var_1': "wario", 'var_2': snakes} return render(request, 'pages/home.html', context=var_dict) Template file (<projectslug>/<projectslug>templates/pages/home.html) {% extends "base.html" %} {% block content %} <table> <thead> <tr> <p>You are on home pg</p> <p>the name is: {{ var_1 }} wa ha ha</p> <p>the second var is: {{ var_2 }} stretch </p> </tr> </thead> </table> {% endblock content %} Settings file (base.py) BASE_DIR = Path(__file__).resolve(strict=True).parent.parent.parent APPS_DIR = BASE_DIR / "projectslug" TEMPLATES = [ { # https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATES-BACKEND "BACKEND": "django.template.backends.django.DjangoTemplates", # https://docs.djangoproject.com/en/dev/ref/settings/#dirs "DIRS": [str(APPS_DIR / "templates")], # https://docs.djangoproject.com/en/dev/ref/settings/#app-dirs "APP_DIRS": True, } All of the text in home.html displays as expected. The problem is accessing the variables within {{ }} brackets. No matter what I try the variables just do not appear. I've cut down the system as it used to pull info from a psql db and populate in a complex table, but have been able to … -
How to get rid of daylight saving time (DST) in Django? (Because in my country it's not being used anymore!)
In my country, daylight saving time (DST) is not being applied anymore, but Django is still taking it into account. So when I choose my region in TIME_ZONE inside the settings.py file, the time is stored wrong (1-hour offset) inside the database. Is there any possible way to turn off the DST in Django?! -
Django Mock isn't working as expected in Unit test
I'm having a view in which there is a method called can_upload_file that makes external calls. So, in my unit test I tried to mock that particular method as follows: DatasetViewSet._can_upload_file = MagicMock() DatasetViewSet._can_upload_file = "valid" response = self.client.post(self.url, self.dataset, format="multipart") However I see that the actual can_upload_file method in the view is still executed. How can I fix this? -
DRF Social OAUTH2 merge email and social login. Error UNIQUE constraint failed: users_user.email
implemented Django Rest Framework social OAUTH following this guide https://abhik-b.medium.com/step-by-step-guide-to-email-social-logins-in-django-5e5436e20591 I create user successfully with email/password and also with google oauth. The issue is the following... If I create a user with email/password (example@gmail.com) and then I try to login with google with the same email (example@gmail.com) i got following error. django.db.utils.IntegrityError: UNIQUE constraint failed: users_user.email See complete log here [02/May/2023 21:03:07] "POST /api-auth/google-tokens/ HTTP/1.1" 200 648 Internal Server Error: /api-auth/convert-token Traceback (most recent call last): File "F:\Luix\Estudio\React\Try-Hard-Apps\try-hard-backend\evns\tryhard\Lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "F:\Luix\Estudio\React\Try-Hard-Apps\try-hard-backend\evns\tryhard\Lib\site-packages\django\db\backends\sqlite3\base.py", line 357, in execute return Database.Cursor.execute(self, query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ sqlite3.IntegrityError: UNIQUE constraint failed: users_user.email The above exception was the direct cause of the following exception: Traceback (most recent call last): File "F:\Luix\Estudio\React\Try-Hard-Apps\try-hard-backend\evns\tryhard\Lib\site-packages\django\core\handlers\exception.py", line 56, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "F:\Luix\Estudio\React\Try-Hard-Apps\try-hard-backend\evns\tryhard\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "F:\Luix\Estudio\React\Try-Hard-Apps\try-hard-backend\evns\tryhard\Lib\site-packages\django\views\decorators\csrf.py", line 55, in wrapped_view return view_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "F:\Luix\Estudio\React\Try-Hard-Apps\try-hard-backend\evns\tryhard\Lib\site-packages\django\views\generic\base.py", line 103, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "F:\Luix\Estudio\React\Try-Hard-Apps\try-hard-backend\evns\tryhard\Lib\site-packages\django\utils\decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "F:\Luix\Estudio\React\Try-Hard-Apps\try-hard-backend\evns\tryhard\Lib\site-packages\django\views\decorators\csrf.py", line 55, in wrapped_view return view_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "F:\Luix\Estudio\React\Try-Hard-Apps\try-hard-backend\evns\tryhard\Lib\site-packages\drf_social_oauth2\views.py", line 47, in dispatch return super(CsrfExemptMixin, self).dispatch(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "F:\Luix\Estudio\React\Try-Hard-Apps\try-hard-backend\evns\tryhard\Lib\site-packages\rest_framework\views.py", line 509, in dispatch response = … -
Which one do you prefer, django vs fast-api?
I got a question. I'm studying Python and Django. However, I heard that the fast-api is now a trend, so I am wondering whether to study Django(django rest framework) more or to study the fast-api again. Which framework do you prefer in practice? If you develop with Python, I would like to know the answer to whether you use django(django rest framework) more or fast-api more in the actual field. I'm wondering which one to prioritize. -
Django Login dont work, how i can i fix it?
I have a functional login feature on my website, but unfortunately, the private page can still be accessed by typing in its URL, even without logging in. I am concerned about this security flaw and would like to know how I can prevent users from accessing the private page without first logging in. Can you offer any advice or guidance on how to address this issue? I asked ChatGPT for help. It suggested putting "login_required" before "def", but it's not working. def login_view(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect('/Händlerpage/ else: return render(request, 'login.html', {'error_message': 'Ungültiger Login'}) else: return render(request, 'login.html') @login_required def Händlerpage(request): return render(request,'Händlerpage.html') -
Django how to update querysets' jsonfield based on current value
According to django docs, queryset could be updated with F expression as qs.update(stories_filed=F('stories_filed')+1) How can we use the F expression on nested jsonfield? Assuming I have a jsonfield as extra_data = models.JSONField(default=dict), and I use extra_data['logs'] to record actions in this model, which means extra_data['logs'] = ['log1', 'log2'] What is required is something like qs.update(extra_data__logs=F('extra_data__logs').append('some logs')) Is there any way to update jsonfield like above? -
Django Admin only showing one record
I just did a migration and now my Django Admin for a specific model is only showing 1 record on the first page, all other pages are emtpty, even though it says there are 40000+ records across 4000+ pages (which there should be - they are in the database). What is happening here? This is on Django 3.0 . -
Django send mail with ics attachment encoding error
I am trying to send an ics attachment to the clients with django: message = EmailMessage(subject, html_string, from_email, [to_email]) if attach: message.attach_file(attach, 'text/calendar; charset=UTF-8') message.send() Before sending the file it has the correct characters (on the server) like: Hajvágás And after I send it, it looks like this: Hajvágás I checked multiple email clients like gmail and spark and all of them show the same gibberish. Also the ics file is validated. Is there a way to send it correctly? -
Make a List Based on the Aggregation of Ratings from Two Models
From two models: class Review(models.Model): artist = models.CharField(max_length=100) album = models.CharField(max_length=200) rating = models.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(10)], default=10, ) ... class AddedReview(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) review = models.ForeignKey(Review, on_delete=models.CASCADE) rating = models.IntegerField(default=10) ... I was able to create a model method in the Review model to aggregate the ratings from both models above: def avg_rating(self): added_ratings = 0 orig_rating = self.rating added_ratings_count = self.addedreview_set.count() if added_ratings_count > 0: for added_review in self.addedreview_set.all(): added_ratings += added_review.rating ratings_sum = added_ratings + orig_rating ratings_count = added_ratings_count + 1 ratings_avg = ratings_sum / ratings_count avg_return = round(ratings_avg, 1) if avg_return == 10.0: avg_return = 10 else: avg_return = avg_return return avg_return else: return self.rating I have the Reviews displayed by the date they were created, with their "Avg. Rating" displayed: Now I want to create a "Highest Rated" list, ordering the list by each Reviews "Avg. Rating": I thought I would be able to do this using the {{ review.avg_rating }} I just created: # views.py highest_list = Review.objects.order_by('-avg_rating')[0:5] # sidebar_component.html (included in home.html) {% for review in highest_list %} <div class="d-flex justify-content-between"> <p class="list-item"><a href="{% url 'review' review.id %}">{{ review.artist }} - {{ review.album }}</a></p><span>{{ review.avg_rating }}</span> </div> {% endfor %} But this … -
'ManyRelatedManager' object has no attribute 'reserve_distance'
I have been trying to retrieve data from database using prefetch_related including a Many-to-Many relationship. However, I am getting the error: AttributeError: Got AttributeError when attempting to get a value for field `reserve_distance` on serializer `ProjectIndianReserveSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `ManyRelatedManager` instance. Original exception text was: 'ManyRelatedManager' object has no attribute 'reserve_distance'. When removing reserve_distance from ProjectIndianReserveSerializer (considering this is a Many-to-many relationship there is a possibility to have zero records), the serialization finishes with no errors showing an empty result after serialization: "nearest_first_nations": { "reserve_id": null }, However, when running the created query (shown below), a record for the project_id =1 exists in the db: SELECT ("project_nearest_first_nations"."project_id") AS "_prefetch_related_val_project_id", "indianreservebanddistance"."id", "indianreservebanddistance"."reserve_id", "indianreservebanddistance"."reserve_distance" FROM "indianreservebanddistance" INNER JOIN "project_nearest_first_nations" ON ("indianreservebanddistance"."id" = "project_nearest_first_nations"."indianreservebanddistance_id") WHERE "project_nearest_first_nations"."project_id" IN (1) I am wondering why is not showing the record in response when I have the record in the db: _prefetch_related_val_project_id|id |reserve_id|reserve_distance| ------------------------------------+---+----------+----------------+ 1|110| 627| 31.1900| 1|111| 660| 39.5800| 1|112| 607| 46.1700| Here is the configuration I have in the models: indian_reserve_name.py (model) class IndianReserveName(models.Model): name = models.CharField(max_length=127) project.py (model) class IndianReserveDistance(models.Model): reserve_id = models.ForeignKey(IndianReserveName, on_delete=models.SET_NULL, db_column="reserve_id", null=True) reserve_distance = models.DecimalField(max_digits=16, decimal_places=4, blank=False, … -
Heroku migrations refuse being made
I deployed a django rest application on Heroku but I noticed when I went to the api route, I see a no such table error. I figured I needed to do heroku run python manage.py makemigrations heroku run python manage.py migrate heroku run python manage.py createsuperuser Which I actually did, I got a lot of OK from running those migrations but then when I decided to create a super user, it says I have 20 unapplied migrations even though I just run the migrate command and got plenty of OKs -
RuntimeError: Parsing error while reading transducer header; wrong or corrupt file?
I am trying to set up a new repo which has very limited instructions. I am getting this error when running "pipenv run python manage.py runserver". The file the error message refers to exists and does not look to be corrupted. What can I do about this? Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/cshome/bsapara/Documents/ALT/recording-validation-interface/.venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/cshome/bsapara/Documents/ALT/recording-validation-interface/.venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/cshome/bsapara/Documents/ALT/recording-validation-interface/.venv/lib/python3.8/site-packages/django/core/management/base.py", line 387, in check all_issues = self._run_checks( File "/cshome/bsapara/Documents/ALT/recording-validation-interface/.venv/lib/python3.8/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/cshome/bsapara/Documents/ALT/recording-validation-interface/.venv/lib/python3.8/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/cshome/bsapara/Documents/ALT/recording-validation-interface/.venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/cshome/bsapara/Documents/ALT/recording-validation-interface/.venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/cshome/bsapara/Documents/ALT/recording-validation-interface/.venv/lib/python3.8/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/cshome/bsapara/Documents/ALT/recording-validation-interface/.venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/cshome/bsapara/Documents/ALT/recording-validation-interface/.venv/lib/python3.8/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/cshome/bsapara/Documents/ALT/recording-validation-interface/.venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 581, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File … -
Websocket connection failed in production. (Nginx, Gunicorn, Daphne) (Django/React)
I am trying to deploy my Django Rest Framework application to production. I have my own server running Debian. I am not new to deploying DRF and React applications and the WSGI part of the application works fine with Gunicorn. The problem I can't solve is I cannot connect to my Websocket from Django Channels no matter what I do. For further information, running python manage.py runserver and running everything locally works, I normally connect to my websocket. My routing.py file: from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path, re_path from apps.chat_app.consumers import ChatConsumer websocket_urlpatterns = [ path('ws/chat/<int:id>/<int:curr>/', ChatConsumer.as_asgi()), ] application = ProtocolTypeRouter({ 'websocket': URLRouter( websocket_urlpatterns ) , }) My consumers file: import json from channels.db import database_sync_to_async from channels.generic.websocket import AsyncWebsocketConsumer from django.contrib.auth import get_user_model from apps.chat_app.models import Message class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): current_user_id = self.scope['url_route']['kwargs']['curr'] other_user_id = self.scope['url_route']['kwargs']['id'] self.room_name = ( f'{current_user_id}_{other_user_id}' if int(current_user_id) > int(other_user_id) else f'{other_user_id}_{current_user_id}' ) self.room_group_name = f'chat_{self.room_name}' await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard(self.room_group_name, self.channel_layer) await self.disconnect(close_code) async def receive(self, text_data=None, bytes_data=None): data = json.loads(text_data) message = data.get('message', '') sender_username = data['sender'].replace('"', '') sender = await self.get_user(username=sender_username) typing = data.get('typing', False) delete = data.get('delete', '') if typing: … -
I can't add a 1st empty option in my select
I have the following form class Report3Form(Form): fecha = ChoiceField( choices = [], widget=Select(attrs={ 'class': 'form-control', }), ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['fecha'].choices = [(f"{d:%Y-%m}", f"{d:%B, %Y}") for d in ConsumoElect.objects.dates("fecha", "month")] That is based on this model: class ConsumoElect(models.Model): pgd = models.ForeignKey(TipoPGD, on_delete=models.CASCADE, related_name='consumoelect') fecha = models.DateField(default=datetime.now) fecha_AM = models.CharField(max_length=20) lec_madrugada = models.IntegerField(default=0) lec_dia = models.IntegerField(default=0) lec_pico = models.IntegerField(default=0) reactivo = models.IntegerField(default=0) dato = models.IntegerField(default=0) total = models.IntegerField(default=0) The form shows a select with the month and its year as if a distinct was used in the ORM, I need the first thing that the select shows to be an empty value that says "select a date". This link shows an example of what I want, but I can't adapt it to my problem In Django how to add a placeholder to a form based on model charfield