Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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'} ), … -
Django Template Table custom cells?
I am playing around with django a bit and wanted to create a table which I'm filling with some whatever. I am very new to programming with django and html. I have 4 for loops (sounds like a lot) {% for row in rows %} <tr> {% for column in columns %} {% for item1 in items1 %} {% if item1.attribute == column.attribute and something %} <td>{{item1.name}}</td> {% endif %} {% endfor %} {% for item2 in items2 %} {% if something %} <td>{{item2.name}}</td> {% endif %} {% endfor %} {% endfor %} </tr> {% endfor %} So as you can see, only if one of the if conditions is true a cell is created. This is obviously not what I want and I know by doing <td> {% for column in columns %} <td> {% for item1 in items1 %} . . . {% endif %} {% endfor %} </td> there would be a cell for every row and column tuple. However I want to individualy add a different background to each of the item types (item.type exists) like <td bgcolor= "color_name | hex_number | rgb_number"> </td>. I first tried a variable {% with emptycell="yes" %} that I change … -
Import Errors for Custom Django Apps in XBlock Development on OpenEdX Palm Version
I’m having trouble importing custom Django apps in an Open edX XBlock. Even though the Django application is installed in the Open edX environment, I'm encountering errors. The video_rating custom Django application is installed and working perfectly in this environment. onlineoffline is my XBlock. 2024-07-22 10:43:36,866 WARNING 32 [xblock.plugin] [user None] [ip None] plugin.py:144 - Unable to load XBlock ‘onlineoffline’ Traceback (most recent call last): File “/openedx/venv/lib/python3.8/site-packages/xblock/plugin.py”, line 141, in load_classes yield (class_.name, cls.load_class_entry_point(class)) File “/openedx/venv/lib/python3.8/site-packages/xblock/plugin.py”, line 70, in load_class_entry_point class = entry_point.load() File “/openedx/venv/lib/python3.8/site-packages/pkg_resources/init.py”, line 2517, in load return self.resolve() File “/openedx/venv/lib/python3.8/site-packages/pkg_resources/init.py”, line 2523, in resolve module = import(self.module_name, fromlist=[‘name’], level=0) File “/openedx/venv/lib/python3.8/site-packages/onlineoffline/init.py”, line 1, in from .onlineoffline import OnlineOfflineClassXBlock File “/openedx/venv/lib/python3.8/site-packages/onlineoffline/onlineoffline.py”, line 4, in from openedx.features.video_rating.models import UserFeedbackSave,Questions,Type,Ratings ModuleNotFoundError: No module named ‘openedx.features.video_rating’ -
Use Custom Manager to Filter on a Reverse Relation
I have a set of users and a set of assignments each user submits. class User(models.Model): name = models.CharField() class Assignment(models.Model): user = models.ForeignKey( "User", related_name="assignments" ) status = models.CharField() approved = AssignmentActiveManager() rejected = AssignmentRejectedManager() ... I created custom managers to determine different states of assignments, as it's complex and should be internal to the model. For example: class AssignmentActiveManager() def get_queryset(self): return Assignment.objects.filter(status__in=["Approved", "Accepted"]) Now I want to get all users with an approved assignment, using the Assignment.approved manager, because I don't want to duplicate the filtering code. I can do Users.objects.filter(assignments__in=Assignments.approved.all()).all() However, this query involves a WHERE status IN (SELECT ...) subquery. This is going to be less efficient than the query generated if I had written the filtering explicitly: Users.objects.filter(assignments__status__in=["Approved", "Accepted"]).all() Which would do an INNER JOIN and WHERE status IN (Approved, Accepted). So my question is. Is there a way to select users by filtering on assignments using the Assignment custom managers efficiently? -
Django project on CS50dev IDE
I am currently working on the CS50 Web course and am focusing on Project 1. For my development environment, I decided to use the online CS50dev IDE because I cannot install Django on my PC due to administrative restrictions. One of the first tasks in the project is to set up routing for files. For example, if you type server_address/wiki/css, you should be able to view the css page (if it exists); otherwise, an error page should be rendered. However, when I run the server and try to view pages, the error page is always displayed instead of the css page (or any other existing page). I suspect the problem might be related to the storage configuration. When I use the debugger to test my get_entry function, I encounter the following error: django.core.exceptions.ImproperlyConfigured: Requested setting STORAGES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Could you please help me figure out this bug? I’ve spent hours researching it, but nothing seems to be working. I tried to configure the storages but that didn't help. -
Django: How to solve multi-dev issue for database that should be populated
I'm working on a project with some people and we've been adding images and some text to the database (Postgres) through the django admin, they get added to the database but when someone commits to the GitHub repository and someone else pulls and runs he doesn't see any of the things added to the database. It looks like django doesn't leave instructions of what to populate to the database in the code itself so how can we get around this issue? Is there a standard method people already use? -
Modify available choices for a multiple Django from based on current selection
I have a form that works with these base choices: class ShockForm(forms.Form): sector = forms.ChoiceField(choices=[ ('c1', 'Choice 1'), ('c2', 'Choice 2'), ('c3', 'Choice 3'), ]) amount = forms.FloatField() the form is rendered a number of times depending on the user's previous selection, it displays n forms if n was inputed by the user on the previous screen. I want to make the forms dynamic, ie, if an user selects one choice in the first form that choice is not available on the other form and so on, so there cannot be duplicated choices. I belive JS is the solution for this as I am not saving every form one by one but all in one go (see views below). However I have very little knowledge of JS and all I tried did not work. Any guidance? Here is the template relevant content: <form method="post"> {% csrf_token %} {% for form in shocks_forms %} <h4>Sector {{ forloop.counter }}</h4> {{ form.as_p }} {% endfor %} <button type="submit">Submit</button> </form> And here the back end view: def simulation_shocks_view(request, pk): simulation = get_object_or_404(Simulation, pk=pk) number_of_sectors_to_shock = simulation.number_of_sectors_to_shock if request.method == 'POST': form_list = [ShockForm(request.POST, prefix=str(i+1), impact_area=simulation.impact_area) for i in range(number_of_sectors_to_shock)] if all(form.is_valid() for form in … -
I cannot figure out why I am still having pathing issues in Django for the Admin Panel as it is having trouble finding the static file
I have changed my Django folder structure quite late in the project, I am new to Django, so I did not prepare the folders at the beginning of the project which is my fault. I have been having issues with the static files, I managed to fix the static files for the project, but my Django Admin panel seems to have issues finding the static files for the admin panel. These are the types of errors that I am getting: WARNING 2024-08-14 09:27:03,080 log 10464 13992 Not Found: /static/admin/css/responsive.css WARNING 2024-08-14 09:27:03,080 log 10464 12416 Not Found: /static/admin/css/nav_sidebar.css WARNING 2024-08-14 09:27:03,080 basehttp 10464 13992 "GET /static/admin/css/responsive.css HTTP/1.1" 404 179 WARNING 2024-08-14 09:27:03,080 basehttp 10464 12416 "GET /static/admin/css/nav_sidebar.css HTTP/1.1" 404 179 The admin panel does load it's just the aesthetic aspects of it not loading, such as the css. This is the folder structure: ├───api │ ├───migrations │ ├───utils ├───assets │ ├───css │ └───images ├───config │ ├───django (This is where the base.py, prod.py, test.py, dev.py files) │ │ └── base.py │ │ └── test.py │ │ └── dev.py │ │ └── prod.py │ ├───settings (This is for storing files such as celery.py) │ ├───env.py │ ├───urls.py ├───templates │ └───includes └───.env └───manage.py … -
Custom Permission Mixin Django Rest Framework
I am trying to create a custom mixim that handles additional permission checks in my views. This is what I have tried: class ProfilePermissionsRequiredMixin: required_permissions = [] def get_required_permissions(self): return self.required_permissions def dispatch(self, request, *args, **kwargs): # Check if the user is authenticated if not request.user.is_authenticated: raise PermissionDenied("You must be logged in to access this resource.") # Get the user's profile profile = request.user.profile # Check if the profile has all the required permissions if all(profile.has_perm(perm) for perm in self.get_required_permissions()): return super().dispatch(request, *args, **kwargs) # Return 403 Forbidden if any permission check fails raise PermissionDenied("You do not have permission to access this resource.") The issue here is that the request that I get is not authenticated. I use a custom authentication class and it is apparently not applied in the despatch. What can I do to fix this? -
Is there a way to fix AuthCanceled error in the google-sign in in Django?
I was just developing my website, adding CustomUsers, managing profiles, etc., and everything went well, but when I tried to add Google Sign In, I kept getting errors in mid-authentication, like: !error image(https://i.sstatic.net/JqgI0S2C.png) or a text description of it: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/accounts/complete/google-oauth2/?state=Ykq4uYjlm2UMCICLCaKNQtDFmb6hEeQf&code=4%2F0AcvDMrA19DF4z27cVgLBo0ZMua4bL0njYqz-XKFiX9cjZ4k_xf9qAAAD_thq74_ghMhRUw&scope=email+profile+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&authuser=0&prompt=consent Django Version: 4.2.14 Python Version: 3.10.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main.apps.MainConfig', 'social_django'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', 'django_user_agents.middleware.UserAgentMiddleware'] Traceback (most recent call last): File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\cache.py", line 62, in _wrapper_view_func response = view_func(request, *args, **kwargs) File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_django\utils.py", line 49, in wrapper return func(request, backend, *args, **kwargs) File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_django\views.py", line 31, in complete return do_complete( File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_core\actions.py", line 49, in do_complete user = backend.complete(user=user, redirect_name=redirect_name, *args, **kwargs) File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_core\backends\base.py", line 39, in complete return self.auth_complete(*args, **kwargs) File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_core\utils.py", line 256, in wrapper return func(*args, **kwargs) File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_core\backends\oauth.py", line 411, in auth_complete state = self.validate_state() File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_core\backends\oauth.py", line 101, in validate_state raise AuthStateMissing(self, "state") Exception Type: AuthStateMissing at /accounts/complete/google-oauth2/ Exception Value: Session value state missing. Please note that I …