Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Running another method in a View after a form is saved using CBVs - DJANGO
I am trying to run another method after a form is saved: The method inc_rec gets the id field created from the class based view once saved Once form is saved: I want to retrieve all records in the table Checklist Iterate through each of the rows and add the records to the All_Inspection table and updating the company id. I am a bit stuck - as I have tried using signals, and I have tried to override, but somewhere there is a gap. Help appreciated - Thanks in advance. class ParishCreateView(LoginRequiredMixin, CreateView): model = Company fields = ['str_Company_Name', 'str_City','str_post_code'] #success_url = '/' def form_valid(self, form): print('form_valid') form.instance.author = self.request.user return super().form_valid(form) def inc_rec(self): Checklist = Checklist.objects.all() id = self.request.id for rec in Checklist: new_rec=All_Inspection(str_status=rec.str_status, str_check=rec.str_check, str_comment='',company_id=id) new_rec.save() I am expecting new records to be added into ALL_Inspection table once the form is saved with the new created item. -
Django All-auth return account inactive at the first social login
I have the local account that status is_active = False. Now I would like to set the account activation status True automatically if users login by their social account. At my code, I have the Django Allauth hook to set the user is_active to True class CustomAccountAdapter(DefaultSocialAccountAdapter): def pre_social_login(self, request, sociallogin): email = sociallogin.email_addresses[0] user = User.objects.get(email=email) user.is_active = True user.save() However, at the first time login, it's always tells me that the account is not active. When login at the second time, users can login as expected, I'm still not figure out why is this happening. please help me with this, thank you. -
Is there a way to connect users from different projects?
My admin dashboard users are in mongodb in authentication server(expressjs ts) but my apps users are in postgresql in another server(Django). I have made once service that is used to create events. but the problem is I want to know who created the event. as the event can be created by both admin users and app users. I am currently using jwt with same secret in both servers and using bearer token to authenticate the user. So far it's working as I am storing the id and name of users in event model. here the id of admin will be from mongodb and id of app user will be from postgresql. Is there a correct way to do this? -
Trigger Function Not Inserting All Records in data_sync_datahistory Table with application_name = 'dibpos_offline'
I'm working on a PostgreSQL trigger function to log changes to a data_sync_datahistory table whenever there's an INSERT or UPDATE operation on other tables. The trigger is set up to only log these changes when the application_name is set to 'dibpos_offline'. However, I'm encountering an issue where some records are not being inserted into the data_sync_datahistory table when multiple records are inserted into the database. Here is my trigger function: IF current_setting('application_name') = 'dibpos_offline' THEN IF TG_OP = 'INSERT' THEN INSERT INTO data_sync_datahistory (created, modified, data, source, table_name) VALUES (CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, ROW_TO_JSON(NEW), 'local', TG_TABLE_NAME); ELSIF TG_OP = 'UPDATE' THEN INSERT INTO data_sync_datahistory (created, modified, data, source, table_name) VALUES (CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, ROW_TO_JSON(NEW), 'local', TG_TABLE_NAME); END IF; END IF; RETURN NEW; And here is the relevant part of my database configuration: DATABASES = { 'default': { 'NAME': os.environ.get('DB_NAME', "postgres") if os.environ.get("DB_HOST", None) else os.path.join(Path.home(), 'dibpos.sqlite3'), 'USER': os.environ.get('DB_USER', "postgres"), 'PASSWORD': os.environ.get('DB_PASSWORD', '1234'), 'HOST': os.environ.get('DB_HOST', ''), 'PORT': os.environ.get('DB_PORT', 5432), 'CONN_MAX_AGE': None, 'CONN_HEALTH_CHECK': True, 'OPTIONS': { 'options': '-c application_name=dibpos_offline' }, } } Problem: When multiple records are inserted into the database, some of them are not being logged into the data_sync_datahistory table. The trigger function seems to be missing some records. Questions: Could the issue … -
Define commonly used form fields in Django
I have an app where there are some search forms on different pages. One commonly used form field would be 'show x items', where x can be 10, 20 or 50. I would also like a field 'Sort by' with some standard values. I have used Django model mixins earlier, e.g. CreateTimestampMixin, which standardizes the column name 'create_ts' in my models, and I want to have something similar in my forms now. Note: These are just forms, not model forms. Is there a way that I can do it? Or must I only define a new field type that derives from forms.ChoiceField, plugin my choice values, and then in each form define this field? -
Nothing happens when you try to start the django server. Writes only to the Python terminal
Nothing happens when you try to start the django server. Writes only to the Python terminal. I work in the VS code editor I was checking Check the path to the interpreter. I checked the Python version. I run it in the folder where it is located manage.py -
Django - can't use different id an value with choicefield's list while using jQuery Editable Select
In Django I'm using a ChoiceField: forms.py class forms_sales_documents(forms.ModelForm): sales_documents_description_1 = forms.ChoiceField(required=False, choices=list(models_products.objects.values_list( 'id_product','product_denomination')), widget=forms.Select(attrs={'id': 'sales_documents_editable_select_description_1','style': 'width:200px','onchange': 'populate_selected_product(this.id,this.value)'})) I'm using JQuery-Editable-select https://github.com/indrimuska/jquery-editable-select to create searchable selecboxes but when I do, it becomes impossible to dissociate the ChoiceField value from the label. They have to be the same like models_products.objects.values_list( 'id_product','id_product')) you can"t do something like models_products.objects.values_list( 'id_product','product_denomination')) otherwise the form won't save and raise the error : Select a valid choice. That choice is not one of the available choices Anybody to help me on this ? -
DigitalOcean IP is sending me to a random website
I am setting up a Django website on DigitalOcean. I've been following along a tutorial and in my settings folder I set my ALLOWED_HOSTS equal to the ipv4 that DigitalOcean provided when I set up the droplet for the project. However when I run python3 manage.py runserver using the provided ip address it sends me over to https://unforgettableweddingaustralia.com/. I'm thinking that DigitalOcean provided me with an IP address already in use but I'm not sure. Any advice or ideas would be greatly appreciated. -
Error 500 on the Heroku server, when locally everything is fine
I made an django app from the "Python Crush Course" book and when I try to login or register in my django app on heroku server, I have an error 500 on webpage and error 200 on logs. However, when I register or login locally I don't have any issues. Here are the heroku logs: 2024-08-02T22:17:13.267743+00:00 heroku\[web.1\]: State changed from starting to up 2024-08-03T22:34:20.389130+00:00 heroku\[router\]: at=info method=GET path="/" host=fierce-brook-34882-87d6631e0056.herokuapp.com request_id=34b832f3-b190-4bc2-88ac-576c6dd59905 fwd="80.107.58.61" dyno=web.1 connect=0ms service=137ms status=200 bytes=2493 protocol=https 2024-08-03T22:34:20.389210+00:00 app\[web.1\]: - - \[03/Aug/2024:22:34:20 +0000\] "GET / HTTP/1.1" 200 2197 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0" 2024-08-03T22:34:20.729350+00:00 app\[web.1\]: 10.1.62.231 - - \[03/Aug/2024:22:34:20 +0000\] "GET /favicon.ico HTTP/1.1" 404 1862 "https://fierce-brook-34882-87d6631e0056.herokuapp.com/" "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0" 2024-08-03T22:34:20.729672+00:00 heroku\[router\]: at=info method=GET path="/favicon.ico" host=fierce-brook-34882-87d6631e0056.herokuapp.com request_id=ba080178-f0ef-4d0c-8745-0556273710f1 fwd="80.107.58.61" dyno=web.1 connect=0ms service=28ms status=404 bytes=2165 protocol=https 2024-08-03T22:34:26.884713+00:00 app\[web.1\]: 10.1.94.152 - - \[03/Aug/2024:22:34:26 +0000\] "GET /users/login/ HTTP/1.1" 200 2715 "https://fierce-brook-34882-87d6631e0056.herokuapp.com/" "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0" Here are the localhosts logs: [arch@archlinux dj_proj]$ python3 manage.py runserver Performing system checks... System check identified no issues (0 silenced). August 14, 2024 - 19:36:06 Django version 5.1, using settings 'learning_log.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [14/Aug/2024 19:36:09] "GET / HTTP/1.1" 200 2197 [14/Aug/2024 19:36:28] … -
Django user_auth how to foreign key one to many
What I'm looking for is that a many users can be part of a tenant, so my idea in the beginning was to foreign key from user to tenant but I can't found how to do this. This is what I have at the moment: models.py class Tenants(models.Model): empresa = models.CharField(max_length=60, null=False, blank=False) sub_dominio = models.CharField(max_length=60, null=True, blank=True) usuario = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE) updated_at = models.DateTimeField(auto_now=True) created_by = models.CharField(max_length=20, null=False, blank=False) class Meta: verbose_name_plural = "Tenants" def __str__(self): return self.empresa But with this solution I can only have a User per Tenant, how can I do Many users per tenant? -
when i use django model's variable for api keys to get data of coinbase market it doesn't work
i have created django models to save the api keys this is the models code class Coinbaseapi(models.Model): symbol = models.CharField(max_length=10, null=True, blank=True) API = models.CharField(max_length=100, null=True, blank=True) SECRET = models.CharField(max_length=250, null=True, blank=True) and using this serializer class Coinbaseserializer(serializers.ModelSerializer): class Meta: model = Coinbaseapi fields = "__all__" I tried getting the market data in a function with this code coinbase = Coinbaseapi.objects.all().first() cbSerializer = Coinbaseserializer(coinbase) CoinbaseData = cbSerializer.data current_price = coinbase.fetch_ticker(CoinbaseData['symbol'])['last'] it gives this error print(coinbase.fetch_ticker(CoinbaseData['symbol'])['last']) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ n = string[0] if isinstance(string[0], int) else ord(string[0]) ~~~~~~^^^ IndexError: index out of range while i used it buy using local variable and tested in another 1 simple python file and it was working fine. coinbase = ccxt.coinbase({ 'apiKey': API, 'secret': SECRET, "enableRateLimit": True, 'options': { 'defaultType': 'future', } }) cp = coinbase.fetch_ticker('MATIC/USDT')['last'] print(cp) I checked on the internet to save it in this format given below -----BEGIN EC PRIVATE KEY----- xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -----END EC PRIVATE KEY----- instead of using this default format below but didn't worked either -----BEGIN EC PRIVATE KEY-----\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n-----END EC PRIVATE KEY-----\n -
Django - ChoiceField to save ID instead of value, and retrieve value from ID on form load
In Django I'm using a ChoiceField named sales_documents_description_1. forms.py #creation of the list def get_product_denomination_list(): list_product_denomination = list((item.product_denomination , item.product_denomination) for item in models_products.objects.all()) return sorted(list_product_denomination) class forms_sales_documents(forms.ModelForm): [...] sales_documents_description_1 = forms.ChoiceField(required=False,choices=get_product_denomination_list, widget=forms.Select(attrs={'id': 'sales_documents_editable_select_description_1','style': 'width:200px','onchange': 'populate_selected_product(this.id,this.value)'})) models.py class models_products(models.Model): id_product = models.CharField(primary_key=True, max_length=50) product_reference = models.CharField(max_length=20) product_denomination = models.CharField(max_length=200) product_prix_achat = models.CharField(max_length=50) I'm trying to show product_denomination in the dropdown menu but store the related id_product in the DB. On form load I would like the selectbox to retrieve the related product_denomination from the id_product initially stored. I tried this : Need to get id instead of selected value in modelchoicefield django and How to store id in database but to show name in modelchoicefield in Django? with no succes. Thanks for help -
How to Safely Add Users to Backend with Google Sign-In?
I’m working on a Flutter app with my own custom backend built in Django. Currently, I have a registration form that accepts an email and password to create a new user in the database. Now, I’m integrating Google Sign-In and wondering how to handle new user registration. After a successful Google sign-in, I receive details like the email, idToken, accessToken, and user ID. I was thinking of sending a request to my backend with the email and using the accessToken as the password to create the user. But is this a safe approach? Should I handle this differently to ensure the security of the authentication process? What’s the best way to securely add a new user to my backend using the data received from Google Sign-In? I’m not using Firebase, just my own Django backend. Any guidance or best practices on how to implement this securely would be greatly appreciated. Thanks! -
Tailwind color class not working in HTMX post result in a Django app
I want to send a form to a Django view via HTMX. After the request, a new span should be inserted in a div with the ID #result. This span has the Tailwind class text-green-500. This works so far (the span is inserted into the div). However, the color of the span does not change to the nice green tone that I expected. This is the Django view: @login_required def create_daytistic(request: HttpRequest) -> HttpResponse: return HttpResponse('<span class="text-green-500">Daytistic erfolgreich erstellt</span>') And this is the Django template: {% extends 'base.html' %} {% block content %} <div class="bg-gray-100"> <div class="min-h-screen flex"> <!-- Sidebar --> {% include 'components/common/sidebar.html' %} <!-- Main content --> <main class="flex-1 p-8" x-data> <div class="flex flex-row"> <div class="bg-white p-6 rounded-lg shadow-lg w-1/2" x-data="{loading: false}" > <h1 class="text-2xl font-bold mb-4">Daytistic erstellen</h1> <p><b>Hinweis</b>: Die Daytistic darf maximal 4 Wochen alt sein.</p> <form hx-post="{% url 'daytistics_create' %}" hx-trigger="submit" hx-target="#result" hx-swap="innerHTML" hx-indicator="#spinner" @submit.prevent="loading = true" @htmx:afterRequest="loading = false" > {% csrf_token %} <label for="date" class="mt-4">Datum: </label> <input x-mask="99.99.9999" placeholder="DD.MM.YYYY" name="date" class="mt-4 bg-white-light text-gray-500 border-1 rounded-md p-2 mb-4 focus:bg-white-light focus:outline-none focus:ring-1 focus:ring-blue-500 transition ease-in-out duration-150 h-11" /> <div id="submit-button-container" class="inline"> <button type="submit" id="submit-button" class="h-11 w-48 bg-gradient-to-r from-lime-500 to-green-500 text-white font-bold py-2 px-4 rounded-md hover:bg-lime-800 hover:to-green-800 … -
Getting error while accessing my site on python anywhere
Getting this error : Something went wrong :-( Something went wrong while trying to load this site; please try again later. Debugging tips If this is your site, and you just reloaded it, then the problem might simply be that it hasn't loaded up yet. Try refreshing this page and see if this message disappears. If you keep getting this message, you should check your site's server and error logs for any messages. Error code: 504-backend. I have created Blog API using drf and frontend app in django templates in same project. the response time for signup taking to much time to load and gives above error. But when i am using same api for local server on my machine it is working why is it happening also there is this message You are in the tarpit. 100% used – 126.38s of 100s. Resets in 2 hours, 35 minutes is it happening because i am in tarpit? i asked chatgpt my error log it gave this The error log indicates that the signup_view is trying to parse a JSON response from an API, but the response body is empty or not valid JSON. Even though my api response from postman … -
How to generate the confirm password reset view with Django?
I have a Django Rest Framework api app. And I try to generate some functionaly for forgot password. At the moment there is an api call availeble for reset password. And a user gets an email with a reset email link. But the problem I am facing is that if the user triggers the reset email link that this results in an error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/reset-password/MjE/cbr2cj-0d6c660c151de4e79594212801241fed/ So this is the views.py file with the function PasswordResetConfirmView class PasswordResetConfirmView(generics.GenericAPIView): serializer_class = PasswordResetConfirmSerializer print("password rest") def post(self, request, uidb64, token, *args, **kwargs): try: uid = urlsafe_base64_decode(uidb64).decode() user = Account.objects.get(pk=uid) print(user) except (TypeError, ValueError, OverflowError, Account.DoesNotExist): user = None if user and default_token_generator.check_token(user, token): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save(user=user) return Response({"message": "Password reset successful."}, status=status.HTTP_200_OK) else: return Response({"error": "Invalid token or user."}, status=status.HTTP_400_BAD_REQUEST) And model account looks: class MyAccountManager(BaseUserManager): @allowed_users(allowed_roles=['account_permission']) def create_user(self, email, password=None, **extra_field): if not email: raise ValueError("Gebruiker moet een email adres hebben.") if not password: raise ValueError("Gebruiker moet een password hebben.") user = self.model(email=email, **extra_field) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), username=username, password=password, ) user.is_admin = True user.is_active = True user.is_staff = True user.is_superadmin = True … -
Django mod-wsgi return empty response
I am trying to deploy a project on windows server with Apache24 on a Windows server. I am fairly new to this but I have spent more than a week trying to figure out what I need to do and what configurations I need to put in. The server is configured to work on HTTPS with a certificate. You can assume that any request coming on 80 or 8080 port is redirected to 443 that all works fine. <VirtualHost *:443> DocumentRoot "${DOCROOT}" ServerName domain SSLEngine on SSLCertificateFile "${SRVROOT}/conf/${SSLCRT}" SSLCertificateKeyFile "${SRVROOT}/conf/${SSLPEM}" SSLCertificateChainFile "${SRVROOT}/conf/${SSLINTCRT}" #SSLCACertificateFile "${SRVROOT}/conf/${SSLROOTCRT}" <Directory "${DOCROOT}/TIPS"> Require all granted </Directory> <FilesMatch "\.(cgi|shtml|phtml|php|py)$"> SSLOptions +StdEnvVars </FilesMatch> <Directory "${SRVROOT}/cgi-bin"> SSLOptions +StdEnvVars </Directory> WSGIScriptAlias / "path/to/wsgi.py" # WSGIScriptAlias / "path/to/test.wsgi" # Alias for static files Alias /static "path/to/static" Alias /media "path/to/media" <Directory "path/to/static"> Require all granted </Directory> <Directory "path/to/media"> Require all granted </Directory> ErrorLog ${SRVROOT}/logs/error-TIPS.log CustomLog ${SRVROOT}/logs/access-TIPS.log combined BrowserMatch "MSIE [2-5]" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0 In the httpd.conf file there are the following relevant configurations aside from some others: RequestHeader unset Proxy early TypesConfig conf/mime.types AddType application/x-compress .Z AddType application/x-gzip .gz .tgz LoadFile "C:/Program Files/Python310/python310.dll" LoadModule wsgi_module "path/to/venv/lib/site- packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd" WSGIPythonHome "path/to/venv" WSGIPythonPath "path/to/TIPS" The weird thing is that if i request anything from … -
Creating new tenant for django-tenants enabled web application, but could not be able to connect
I have created a multi tenants based web application by using django-tenants package. Earlier i have created two tenants on it and they are working fine. Now i am creating one more tenant by using following method:- from customers.models import Client, Domain lspsk = Client(schema_name='lspsk1', name=' lspsk1', paid_until='2025-09-01', on_trial=True) lspsk.save() domain = Domain() domain.domain = 'lspsk.maumodern.co.in' domain.tenant = lspsk domain.is_primary = False domain.save() I also created DNS entry for the tenant. But when i am connecting to the server i am getting internal server error 500 in browser. When i checked the log file there is one entry like:- 47.9.78.243 - - [14/Aug/2024:10:43:04 +0000] "GET / HTTP/1.1" 500 3058 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36" 47.9.78.243 - - [14/Aug/2024:10:43:04 +0000] "GET /favicon.ico HTTP/1.1" 404 3103 "https://lspsk.maumodern.co.in/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36" Kindly guide me where i am doing wrong what logs should i look to further investigate the issue. Thanks & Regards Neha Singh -
Django stripe expand data to webhook
i sending order data by post request to stripe and creating session and set my order data in line_items, problem is that i want this line_items data to expand to stripe webhook view and by this data creating order and payment history, i tryed first to set this data to metadata={"data": items} but i get error, because is limited count of keys, it's means that my data is too big to put in metadata, after that i found in that i can put my data in expand like that expand=['line_items'] but nothing happend i don't get this data in my webhook view, but i get this data on stripe website so here is my code i hope someone helps me :p from django.conf import settings from django.http import HttpResponse from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from django.views.decorators.csrf import csrf_exempt import stripe from rest_framework.decorators import api_view from accounts.models import AppUser stripe.api_key = settings.STRIPE_SECRET_KEY class StripeCheckoutView(APIView): def post(self, request): try: data = request.data['orderData']['orderItems'] items = [] for i in data.keys(): i = data[i] desc = ', '.join([i.get('name') for i in i.get('extra').values()]) + i.get('extra_info') name = ', '.join( filter(None, [ i.get('name'), i.get('pizzaDough', ''), f"{str(i.get('size', ''))} size" if … -
error while deploying Django project in virtual private server in hostinger
when i try to start nginx its works well but i cant see my site in my domain and when i looks for a error log its says this " gunicorn[313208]: [2024-08-14 05:56:29 +0000] [313208] [ERROR] Connection in use: ('0.0.0.0', 8000) " so i run this command " sudo lsof -i :80 " to check which process is using this port. I saw that these " COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME nginx 316452 root 6u IPv4 1073432 0t0 TCP *:http (LISTEN) nginx 316452 root 7u IPv6 1073433 0t0 TCP *:http (LISTEN) nginx 316453 www-data 6u IPv4 1073432 0t0 TCP *:http (LISTEN) nginx 316453 www-data 7u IPv6 1073433 0t0 TCP *:http (LISTEN) " process are using the port which are my nginx. even though i kill that ports using this sudo kill -9 316452 316453 command. Its still appearing again. can anyone help ? tried these codes already gunicorn[313208]: [2024-08-14 05:56:29 +0000] [313208] [ERROR] Connection in use: ('0.0.0.0', 8000) sudo lsof -i :80 sudo kill -9 316452 316453 -
I get an error when I want to save messages in a real-time chat application in Django
I don't get any error like this import json from channels.generic.websocket import AsyncWebsocketConsumer from channels.db import database_sync_to_async from .models import ChatRoom class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = f'chat_{self.room_name}' await self.create_or_update_room(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): # Odayı terk et await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message } ) async def chat_message(self, event): message = event['message'] await self.send(text_data=json.dumps({ 'message': message })) @database_sync_to_async def create_or_update_room(self, room_name): room, created = ChatRoom.objects.get_or_create(name=room_name) ############################################# (env) PS C:\Users\Serkan\Desktop\stock_trackings\stock_tracking> daphne -p 8000 stock_tracking.asgi:application "C:\Users\Serkan\Desktop\stock_trackings\env\Lib\site-packages\django\apps\registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "C:\Users\Serkan\Desktop\stock_trackings\env\Lib\site-packages\django\apps\registry.py", line 138, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I get an error when I checked the settings, I checked the applications, and when I continue without saving the messages, it works without any problems. -
In django in same web page i need to cnnect both firebase and sql databases. But it is not retrieving sql data when it done
Sql database can not taken to the django although i entered database credentials correctly. A way to connect my sql database with django and is it ok to do it creating models without using sql database Firebase also connected with credentials with its configuration.But if firebasedata loaded sq data not working.On the other hand sql data loaded firebase data not coming. When i place the configuration part to another place of the code it working -
Django Error: "'type' object is not iterable"
i'm a Django beginner and want to write a website for my friend who works as a painter. i wanted to write a rest-api so i can access the models in my frontend (which i didnt implement yet). when i try to call the subdomain for a model i wrote i get the error "'type' object is not iterable". i wanted to make it possible for users that are registered to leave a feedback, so i wrote a class Feedback. I also implemented a FeedbackSerializer and a FeedbackView. i was trying to use chatgpt but that was of no help. stackoverflow also didnt have any similar errors like the one that occured to me. so i came here for help. maybe you guys can help me out. here's what i came up with so far: # api/models.py class Feedback(models.Model): title = models.CharField(max_length=1000, null=False, blank=False) feedback = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) image = models.FileField( upload_to="image", default="default/default-user.jpg", null=True, blank=True) rating = models.IntegerField( validators=[MinValueValidator(1), MaxValueValidator(5)], null=False, blank=False) def __str__(self): return self.title def save(self, *args, **kwargs): super(Feedback, self).save(*args, **kwargs) # api/serializers.py class FeedbackSerializer(serializers.ModelSerializer): class Meta: model = api_models.Feedback fields = "__all__" # api/views.py class FeedbackView(generics.RetrieveAPIView): permission_classes = [AllowAny] serializer_class = api_serializer.FeedbackSerializer def get_object(self): … -
Struggling to control Django caching
My Django app is connected to a Postgresql database via the ORM abstraction. The tables in the database are refreshed every few hours via processes completely separate to the Django app. I am not aware of any database caching in the settings.py - I have not added any and am just using the template setup. However I have noticed that Django doesn't show the refreshed data. The only way to reflect this seems to be via a gunicorn restart on the server. I have read through the caching docs but am not sure where the caching is taking place - in the browser or in the django app. Ideally I would like caching to be used for performance purposes but whenever the browser is reloaded or refreshed the latest data is rendered. Any suggestions on how to do this or link useful documentation outside of the django caching doc? -
a Doctor Appointment Booking Using Django Forms
my booking <div class="accordion" id="accordionExample"> <div class="accordion-item"> <h2 class="accordion-header" id="headingOne"> <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> نزدیک ترین زمان </button> </h2> <div id="collapseOne" class="accordion-collapse collapse show" aria-labelledby="headingOne" data-bs-parent="#accordionExample"> <div class="accordion-body"> ... </div> </div> </div> <div class="accordion-item"> <h2 class="accordion-header" id="headingTwo"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo"> انتخاب دستی </button> </h2> <div id="collapseTwo" class="accordion-collapse collapse" aria-labelledby="headingTwo" data-bs-parent="#accordionExample"> <div class="accordion-body"> {% for bookable in bookables %} <p>{{ bookable.day }} - {{ bookable.start_time }} - {{ bookable.end_time }} - {{ bookable.booking.date }}</p> {% empty %} <p>No bookables available.</p> {% endfor %} </div> </div> </div> </div> my bookable form <form class="modal-body" method="post"> {% csrf_token %} <div class="row justify-content-around"> <div class="col-lg-5"> <label for="{{ form.start_time.id_for_label }}" class="d-block w-100 text-muted"> زمان شروع </label> {{ form.start_time }} <label for="{{ form.end_time.id_for_label }}" class="d-block w-100 text-muted"> زمان پایان </label> {{ form.end_time }} </div> <div class="col-lg-5"> <label for="{{ form.day.id_for_label }}" class="d-block w-100 text-muted"> روز های ویزیت </label> {{ form.day }} <label for="{{ form.capacity.id_for_label }}" class="d-block w-100 text-muted"> ظرفیت </label> {{ form.capacity }} </div> </div> <button class="btn btn-success px-5 p-2 mt-4 rounded-md"> ذخیره </button> </form> my form class BookableForm(forms.ModelForm): class Meta: model = Bookable fields = "__all__" widgets = { 'start_time': forms.TimeInput( attrs={'class': 'form-control mb-3', 'data-jdp': 'data-jdp', 'autocomplete': 'off'} ), …