Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
vscode file not appearing in visual studio while setting up the python interpreter for django
to add the interpreter i go to "view" and then "command palette" and then i select "python: select interpreter" then i enter the interpreter path, the tutorial that im following says that a new file called vscode will appear but it doesnt appear for me, what am i suppose to do? im using visual studio code on windows and im trying to learn django i entered the interpreter path and i was expecting that the vscode tab/file will appear on the explorer tab in visual studio -
getting a "invalid user or password" error while testing a api
I am trying to built an log in API but getting a a "invalid user or password" error while testing. I have checked the database and user and password is correct and exists and correct. I have attached the log in view code and the error as a PNG format below enter image description here it is the log in view enter image description here and here is error. how to solve this issue ? I have checked database and user exists and I also printed user and password in terminal and the user and password also correct but still getting the error -
Whats the use of DSA in real world application?
Okay, I might sound stupid but I'm trying to understand the real-world application of DSA? I started learning DSA but I didn't know what I'm gonna make once I learned the whole thing? I'm a full stack developer and I know if there is a frontend developer his work is to code a site from a figma file or take the API coming from the backend and use Redux or other state management to do stuff or if there is a backend developer I know his work is to make backend parts building APIs working with DB and other stuff... But after learning DSA what I'm gonna build? What kind of work am I gonna do? Or after learning where I can use my DSA knowledge in my web apps? All I see are people talking about FAANG companies online and I haven't found that many videos or blogs on some DSA project in python. Can someone please clear my doubts it would be really appreciated I'm so confused right now. -
Django startproject [WinError2]
This is my first time using django so maybe I am missing something obvious. When I try to create a new project using command django-admin startproject main i get this error CommandError: [WinError 2] The system cannot find the file specified: 'C:\\Users\\edgar\\Documents\\main'. I thought django creates this directory? That's what I see in all tutorials. Very confused I tried running command prompt as an administrator as well as uninstalling and reinstalling django. Also tried reinstalling python which still didn't work. Tried running in VSCode terminal. Nothing seems to be working. If I manually create the directory then i get an error saying 'manage.py' does not exist in the directory. -
Python - Django - MySQL #need to add distinct() after select_related().distinct() in views.py
class AdListView(ListView): model = Ad # Specify the model you're working with template_name = "ads/ad_list.html" def get(self, request): strval = request.GET.get("search", False) if strval: query = Q(title__icontains=strval) query.add(Q(text__icontains=strval), Q.OR) ad_list = Ad.objects.filter(query).select_related().distinct().order_by('-updated_at') else: ad_list = Ad.objects.all().select_related().distinct().order_by('-updated_at') # Apply distinct() explicitly ad_list = ad_list.distinct() if request.user.is_authenticated: favorites = list(request.user.favorite_ads.values_list('id', flat=True)) else: favorites = [] for obj in ad_list: obj.natural_updated = naturaltime(obj.updated_at) ctx = {'ad_list': ad_list, 'favorites': favorites, 'search': strval} return render(request, self.template_name, ctx) so this is ads/views.py there's a ads/models.py, ads/forms, ads/urls.py and other files, but the one that the grader is complaining is this views.py... 3806 characters of HTML retrieved Test completed: Found menu bar at the top of the page Found more than one ad when searching for 'HHGTTG_42 1717639962'. You probably need to add distinct() after select_related().distinct() ... in your views.py so i tried using the select_related().distinct() and adding it after, but is not working :( -
Django: Better way to process data from my models.py than doing it in my views.py
Currently, I am processing a lot of information in views.py, which feels like the incorrect place to do it. Is there a better/place way to process this information? It works, but it doesn't seem like I am using Django to its potential. views.py - Where I am doing all the information processing def stats(request): user = request.user deck_list = Deck.objects.filter(user=request.user).annotate( win_count=Count('game', filter=Q(game__outcome='Win', game__user=request.user)), loss_count=Count('game', filter=Q(game__outcome='Loss', game__user=request.user)), draw_count=Count('game', filter=Q(game__outcome='Draw', game__user=request.user)), incomplete_count=Count('game', filter=Q(game__outcome='Incomplete', game__user=request.user)), count_1_7=Count('game', filter=Q(game__mull='1st 7', game__user=request.user)), count_2_7=Count('game', filter=Q(game__mull='2nd 7', game__user=request.user)), count_6=Count('game', filter=Q(game__mull='6', game__user=request.user)), count_5=Count('game', filter=Q(game__mull='5', game__user=request.user)), count_4=Count('game', filter=Q(game__mull='4', game__user=request.user)), count_3=Count('game', filter=Q(game__mull='3', game__user=request.user)), count_2=Count('game', filter=Q(game__mull='2', game__user=request.user)), count_1=Count('game', filter=Q(game__mull='1', game__user=request.user)), ) # Totals for player total_game = Game.objects.filter(user=request.user).count() total_win = Game.objects.filter(user=request.user, outcome='Win').count() total_loss = Game.objects.filter(user=request.user, outcome='Loss').count() total_draw = Game.objects.filter(user=request.user, outcome='Draw').count() total_incomplete = Game.objects.filter(user=request.user, outcome='Incomplete').count() average_hand_size1_7 = Game.objects.filter(user=request.user, mull='1st 7').count() average_hand_size2_7 = Game.objects.filter(user=request.user, mull='2nd 7').count() average_hand_size6 = Game.objects.filter(user=request.user, mull='6').count() average_hand_size5 = Game.objects.filter(user=request.user, mull='5').count() average_hand_size4 = Game.objects.filter(user=request.user, mull='4').count() average_hand_size3 = Game.objects.filter(user=request.user, mull='3').count() average_hand_size2 = Game.objects.filter(user=request.user, mull='2').count() average_hand_size1 = Game.objects.filter(user=request.user, mull='1').count() average_hand = 0 if total_game == 0: pass else: average_hand = (average_hand_size1_7 * 7 + average_hand_size2_7 * 7 + average_hand_size6 * 6 + average_hand_size5 * 5 + average_hand_size4 * 4 + average_hand_size3 * 3 + average_hand_size2 * 2 + average_hand_size1) / total_game context = … -
Change widget of modelformset field to RadioSelect without defining a form object?
In Django, I am instantiating a modelformset as follows (straight from here): MyFormSet = modelformset_factory( MyModel, fields=["one", "two", "three"], extra=0) fs = MyFormSet(queryset=MyModel.objects.filter(field=a_value)) So, no form object at all, it just picks the fields I want. However, one of those fields (say "two") is rendered as a drop-down, and I want it as a RadioSelect. Is there a way to change the widget of "two" to RadioSelect in a simple way, or do I have to declare a form object to customize that? -
In my django project my post method are showing Not allowed. Why?
This is my CustomToken class in views.py class CustomTokenObtainPairSerializer(TokenObtainPairSerializer): username_field = 'email' def validate(self, attrs): credentials = { 'email': attrs.get('email'), 'password': attrs.get('password') } print("Credentials:", credentials) print("Attrs:", attrs) user = authenticate(**credentials) if user: if not user.is_active: raise exceptions.AuthenticationFailed('User is deactivated') data = {} refresh = self.get_token(user) data['refresh'] = str(refresh) data['access'] = str(refresh.access_token) return data else: raise exceptions.AuthenticationFailed('No active account found with the given credentials') class CustomTokenObtainPairView(TokenObtainPairView): serializer_class = CustomTokenObtainPairSerializer This is my urls.py: urlpatterns = [ path('', include(router.urls)), path('token/', CustomTokenObtainPairView.as_view(), name='token_obtain_pair'), path('register/', UserCreateView.as_view(), name='register'), path('token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'), ] this is my settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.AllowAny', ), } whenever i try to make a request to the user/token/ i get this response: Method Not Allowed: /users/register/ [06/Jun/2024 00:57:45] "POST /users/register/ HTTP/1.1" 405 41 ....or sometimes i get : { "detail": "Authentication credentials were not provided." } Unauthorized: /users/token/ [06/Jun/2024 00:42:40] "POST /users/token/ HTTP/1.1" 401 58 Unauthorized: /users/token/ [06/Jun/2024 00:42:45] "POST /users/token/ HTTP/1.1" 401 58 Can someone explain what's wrong with this? Thank you..... -
DjangoError: AttributeError: 'str' object has no attribute '_meta'. I can't understand the reason and the cause
I have two classes that are accessed according to a specific condition, i.e. if the id of the data_source is 16, I need to bring the data in the graphql query from one entity, and if it is any other id, I need to return it from another entity. I know it's a bad architecture, but I have no power to change it, I just need to complete this task. In this case, I thought of creating an adapter that reads this id from the data_source and, based on this, returns the correct entity in the query. I've been trying to do this all afternoon, and I always get the error below: “Could not import ‘api.schema.schema’ for Graphene setting ‘SCHEMA’. AttributeError: 'str' object has no attribute '_meta'.” I've tried literally everything, I'm going crazy. Im using linux Ubuntu. The stack is: Django + Graphql + PostreSQL We are not using django migrations, our models just use the django orm to retrieve data and make CRUD operations from the db These are the files I've worked on so far: my adapter class: filepath: api/app_risk_rules/models/risk_rule_config_parameters_adapter.py from app_risk_rules.models.risk_rule_config_parameters_journey_item import ( RiskRuleConfigParametersJourneyItem, ) from app_risk_rules.models.risk_rule_config_parameters_values import ( RiskRuleConfigParametersValues, ) class RiskRuleConfigParametersAdapter: DATA_SOURCE_JOURNEY_IDS = ["16"] … -
Should I use Celery to covert audio files on my server
So I have higher quality user audio submissions and I need the server to create lighter .mp3 copies and im wondering if I should use Celery with my django app or use build in Linux tools to control this? I want to control how much processing converting takes to avoid a situation where multiple people submit their audio and the processing uses so much server resources that it compromises the user experience of the app. I have an ubuntu vm in cloud. I use Django with NGINX and gunicorn. -
Django testing: how to keep only one of several test databases?
Seems like this should be simple. If I have something like this in my Django settings.py: DATABASES = { 'default': { ... }, 'second': { ... }, 'third': { ... }, } By default, when unit tests run, all three databases are rebuilt, by applying all the migrations. However, I don't want to rebuild the "expensive" database "three," but using the --keepdb option is obviously not specific enough, as that keeps all the databases. How do I only keep database "three" when running unit tests? Thank you in advance. -
upload a file with django form, request.FILES is empty no matter what I do
when I submit the file and check in the POST of the request from the browser inspector I see all the other fields but not the file field. Accessing request.FILES['attachment'] causes an error django.utils.datastructures.MultiValueDictKeyError: 'attachment' My Model class Ticket(models.Model): attachment = models.FileField(blank=True) title = models.CharField(max_length = 250,default='') My Form class NewTicketForm(forms.ModelForm): attachment = forms.FileField(required = False) My Template <form enctype="multipart/form-data" id="ticketform" method="POST" action=""> {{ form.non_field_errors }} {{ form.title }} {{ form.attachment }} <input type="submit" name="submit_new_ticket" value="Submit"> </form> My View def createNewTicket(request): if request.method == 'POST': form = NewTicketForm(request.user, request.POST) if form.is_valid(): obj = form.save() return HttpResponse(request.FILES["attachment"]) I CANNOT GET IT MANAGED AUTOMATICALLY, I NEED DIRECT ACCESS TO request.FILES -
How to solve the xmlsec Error: (100, 'lxml & xmlsec libxml2 library version mismatch')
I am facing the following error when deploying my Django (version 4.1) Backend, I have the following Dockerfile (some non-relevant parts omitted) and need to install python3-saml (which has dependencies like lxml and xmlsec). The documentation mentions the following: Hence I added the command in the Dockerfile. FROM python:3.10.6 # Install necessary packages RUN apt-get update && \ apt-get install -y s3fs pkg-config libxml2-dev libxmlsec1-dev libxmlsec1-openssl libxmlsec1 && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* # set work directory WORKDIR /usr/src/app # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt RUN pip install python3-saml && \ pip install --force-reinstall --no-binary lxml lxml # copy project COPY . . # create cache directory RUN mkdir -p /var/tmp/django_cache ENTRYPOINT ["./docker-entrypoint.sh"] I am able to build it without problem but upon deployment, I get the following error: File "/usr/local/lib/python3.10/site-packages/onelogin/saml2/auth.py", line 12, in <module> import xmlsec xmlsec.Error: (100, 'lxml & xmlsec libxml2 library version mismatch') I am not sure which library version is expected in this case, I have tried with pip install --no-binary lxml==4.6.3 lxml==4.6.3 --force-reinstall instead, as well as with version 4.9.3 (as seen in other recent threads) but with no success. … -
Making a Django application enterprise ready
What are the must have features over and above the standard Django deployment checklist one should consider to make the application truly enterprise ready. A few things that I can think of are: Access Logs Audit Logs MFA/SSO for user authentication I know there can be tons of things on the infrastructure side but I am focussing on the application side stuff only. Researched on the internet for suggestions but not able to find any authoritative source. Would be great to learn from the experiences of SO members. -
not able to open web page using django
I'm using the code below code for opening a webpage (my_app1) using django in Google Cloudshell, after running server showing below error in serverlink). Using the URLconf defined in demoproject.urls, Django tried these URL patterns, in this order: admin/ ^my_app1/$ The empty path didn’t match any of these. urls from django.urls import include, re_path from django.contrib import admin from .views import my_app, my_ap urlpatterns = \[ re_path(r'admin/', admin.site.urls), re_path(r'^my_app1/$', my_ap), \] views from django.shortcuts import render from django.http import HttpResponse def my_app(request): return HttpResponse("this is response") def my_ap(request): return HttpResponse("hi buddy") How do I get the response hi buddy after running server? -
KeyError: 'type' in a websocket_receive
I have two different apps in my Django project. While the first one (the one with the error raising consumers.py) works fine on its own, the second one keeps raising this: \chat\consumers.py", line 29, in websocket_receive if event['type'] == 'message': KeyError: 'type' chat\consumers.py: from channels.consumer import SyncConsumer, AsyncConsumer from channels.db import database_sync_to_async from asgiref.sync import async_to_sync, sync_to_async from django.contrib.auth.models import User from chat.models import Message, Thread, UserSetting import json from rich.console import Console console = Console(style='bold green') online_users = [] class WebConsumer(AsyncConsumer): async def websocket_connect(self, event): self.me = self.scope['user'] self.room_name = str(self.me.id) online_users.append(self.me.id) await self.channel_layer.group_add(self.room_name, self.channel_name) await self.send({ 'type': 'websocket.accept', }) console.print(f'You are connected {self.room_name}') async def websocket_receive(self, event): event = json.loads(event['text']) #console.print(f'Received message: {event["type"]}') if event['type'] == 'message': msg = await self.send_msg(event) await self.send_users(msg, [self.me.id, self.them_user.id]) elif event['type'] == 'online': msg = await self.send_online(event) console.print(online_users) await self.send_users(msg, []) elif event['type'] == 'read': msg = await sync_to_async(Message.objects.get)(id=event['id']) msg.isread = True await sync_to_async(msg.save)() msg_thread = await sync_to_async(Thread.objects.get)(message=msg) await self.unread(msg_thread, int(event['user']), -1) elif event['type'] == 'istyping': console.print(self.me, event) await self.send_istyping(event) async def websocket_message(self, event): await self.send( { 'type': 'websocket.send', 'text': event.get('text'), } ) async def websocket_disconnect(self, event): console.print(f'[{self.channel_name}] - Disconnected') event = json.loads('''{ "type": "online", "set": "false" }''') online_users.remove(self.me.id) msg = await … -
How to Connect Django 5.0.6 to MSSQL 16?
Is there any way to use MSSQL Server with Django 5.0? I know it's not the most common database for Django, but it would be very suitable for my project for various reasons. Any guidance or tips on setting this up would be really appreciated! -
Telegram mini app preview and test on localhost
I am currently working on developing a mini app, which is essentially a website built on a Django project and served locally using the development server. However, I have been facing slow loading times when trying to view this mini app on a Telegram bot, particularly when using services like ngrok. While other website URLs load quickly, the ngrok setup for my Django project is taking approximately 10 minutes to load. I have also experimented with using an SSL server from** django-sslserver** by running the command: python manage.py runsslserver 0.0.0.0:8000 I hoped that loading the app over HTTPS might improve the speed, but unfortunately, I still encountered the broken pipe error. I have not yet utilized a dedicated server for static files. Do you think incorporating one could help improve the loading speed during local development? ngrok functions smoothly and loads quickly with simple HTTP requests for webhooks or basic HTML files. Therefore, I suspect that the sluggish loading speed may be due to the volume of static files being loaded. I am seeking advice on faster and more efficient methods or tricks to preview my mini app during development using localhost or any alternative approaches. Any suggestions or recommendations … -
Unable to connect django application to Microsoft SQL Database
I have a django application that attempts to connect to an external microsoft sql database from azure. After setting up the database connection parameters in the settings file and installing the odbc driver on my local machine, running the python manage.py makemigrations throws the following error: Here is the settings.py file DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'HOST': DB_HOST, 'PORT': DB_PORT, 'NAME': DB_NAME, 'USER': DB_USER, 'PASSWORD': DB_PASSWORD, 'OPTIONS': { 'driver': 'ODBC Driver 18 for SQL Server', 'encrypt': 'yes', 'trustServerCertificate': 'no', } }, -
Django, React, Axios returning html instead of json data
I am working on a web app with Django Rest Framework and React. When I make a request to Django via http://localhost:8000/api/v1/auth/users/daniel/ for a User's profile, it's returning html instead of the JSON response of the userProfile. Reponse <!doctype html> <html lang="en"> <head> <script type="module"> import RefreshRuntime from "/@react-refresh" RefreshRuntime.injectIntoGlobalHook(window) window.$RefreshReg$ = () => {} window.$RefreshSig$ = () => (type) => type window.__vite_plugin_react_preamble_installed__ = true </script> <script type="module" src="/@vite/client"></script> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Vite + React</title> </head> <body> <div id="root"></div> <script type="module" src="/src/main.jsx?t=1717529669140"></script> </body> </html> Here is the DRF response of what I am expecting to see in the Reac Axios response. urls.py urlpatterns = [ ....., path('api/v1/auth/users/<str:username>/', views.UserProfileByUsernameView.as_view(), name='user-profile-by-username'), ] views.py class UserProfileByUsernameView(APIView): permission_classes = [AllowAny] def get(self, request, username): user = get_object_or_404(User, username=username) profile_serializer = UserProfileSerializer(user.userprofile) profile_data = profile_serializer.data profile_data['username'] = user.username profile_data['email'] = user.email return Response(profile_data, status=status.HTTP_200_OK) serializers.py class UserProfileSerializer(serializers.ModelSerializer): username = serializers.CharField(source='user.username', read_only=True) email = serializers.EmailField(source='user.email', read_only=True) class Meta: model = UserProfile fields = '__all__' profile-page.jsx const ProfilePage = () => { const { username } = useParams(); const [userProfile, setUserProfile] = useState(null); const [isOwnProfile, setIsOwnProfile] = useState(false); const loggedInUsername = localStorage.getItem('username'); useEffect(() => { const fetchUserProfile … -
Asynchronous migrations for django/wagtail
I am working with my friends on wagtail school project, we are working at the same time on our project and making different pages at the same time. We would need a asynchronous system for migrations of pages. I have searched and found command dumpdata and loaddata but this seems that it is synchronous only, and it is not possible for two people to have 2 open Merge requests since dumped json files would override each other. Is there any solution for this problem? -
(DJango) What is the solution to "ModuleNotFoundError: No module named'rest_frameworks'" if nothing works?
I followed a tutorial on youtube and was then faced with such a problem. I tried to find a solution, but nothing worked for me. Maybe something's wrong with my IDE or anything? I checked everything and was unable to find the exact problem. Compared to the script from the video, I think everything is pretty fine ;( -
Annotate Django JSONField to convert all values to strings
I'm using Django's full text search features, and want it to search through a model called Row, which has a JSONfield .data that has a value like: [["A1", 87, 987, "blue"], ["B1", null, null, "white"]] Code to do the search: search_vector = SearchVector('data') search_query = SearchQuery(query) search_headline_data = SearchHeadline('data', search_query, highlight_all=True) results = Row.objects.all() .annotate(search=search_vector) .annotate(headline_data=search_headline_data) When query="blue", the match is a string, and highlighted correctly: [["A1", 87, 987, "<b>blue</b>"], ["B1", null, null, "white"]] But when query="87" so there's a match with an integer, the match is not highlighted. [["A1", 87, 987, "blue"], ["B1", null, null, "white"]] This makes me want to cast all values in the .data JSONField to a string, but I can't find out how to do this through annotation. -
Making WEB-Scada system
Good afternoon, I'm writing a django web scada system at school, please tell me which toolkit is better to use for polling OPCUA hardware with data output without restarting the server I tried to create a separate service in python for the survey, followed by writing data to JSON format, but it seems terribly inconvenient to me, are there any alternatives -
How to change Celery worker concurrency in Django app
Recently I noticed that celery eats up a lot of memory in the server. One instance eating like 10% of mem in processed I see quite default situation: /usr/local/bin/python -m celery -A apps worker -l INFO -c 4 --logfile celery_worker.log With threads it goes up to 14 instances My idea was to cut concurrency to 2 (from process I suggest it is set to 4) I've tried to do it in django settings CELERY_WORKER_CONCURRENCY = 2 and event put in celery file app.conf.update( task_soft_time_limit=60 * 60 * 1, # 2 hours, task_time_limit=60 * 60 * 2, # 3 hours, worker_concurrency=2 # 2 workers ) But it did not work. I've checked it with celery -A apps inspect stats "max-concurrency": 4, "max-tasks-per-child": "N/A", but for example timeout was precessed correctly can you suggest how to solve it?