Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem related to login and profile page
I am working on a python Django project. I have a little problem, When I make login through login form after registration. the main page was redirected to login page again despite configuring it to be redirected to profile page. I tried many solutions and found no solutions This is the Github repo link for the project: https://github.com/Demo-23home/vacc/tree/main What's the solution please? -
Check if object has parent and a grandparent
I'm developing a website with a 3-level hierarchy of pages, so each page may have a parent and a "grandparent" (actually, a parent of parent) page. In my PageUpdateView I have a get_success_url, which should return different URLs, depending of, whether the page has a parent and a grandparent, such as: "/grandparent/parent/page/", "/parent/page/", or "/page/". So, I need to check if a page has a parent and a grand parent. I have tried such a way: def get_success_url(self): if self.object.parent.parent: return reverse('about:detail', kwargs={'grandparent': self.object.parent.parent.slug, 'parent': self.object.parent.slug, 'page': self.object.slug }) elif self.object.parent: return reverse('about:detail', kwargs={'parent': self.object.parent.slug, 'page': self.object.slug }) else: return reverse('about:detail', kwargs={'parent': self.object.parent.slug, 'page': self.object.slug }) Also, I've tried to make a condition: if self.object.parent.parent.exists But every time I get an Error: 'NoneType' object has no attribute 'parent' or 'NoneType' object has no attribute 'exist'. Please give me a hint how to check if an object has a parent and a grandparent. -
How to use Many to Many widget presented in Admin page
I want to use the widget presented in Admin page for Group creation in my Modelform (picture below) but I'm failing in do that. Does anyone know how can I use a widget like this in my form? I have two models that have a many-to-many relationship. I have also created a ModelForm class to get all first_model objects that are related to my second_model. -
Django REST, creating a M2M record
I'm trying to create an instance of UserTrackRelationship, which is the through model. I've omitted as much as I could that didn't seem relevant for this thread. models.py class User(models.Model): class Meta: ordering = ['created'] def save(self, *args, **kwargs): super(User, self).save(*args, **kwargs) class Track(models.Model): track_user_relationships = models.ManyToManyField( User, through='UserTrackRelationship', through_fields=('track', 'user'), ) class Meta: ordering = ['created'] def save(self, *args, **kwargs): super(Track, self).save(*args, **kwargs) class UserTrackRelationship(models.Model): REALTIONSHIP_CHOICES = (('user_owns_track', 'This User Owns This Track'), ('user_watching_track', 'This User Is Watching This Track'), ('user_purchased_copy', 'This User Has Purchased a Copy of This Track')) user = models.ForeignKey(User, related_name='usertrackrel_user', on_delete=models.CASCADE) track = models.ForeignKey(Track, related_name='usertrackrel_track', on_delete=models.CASCADE) relationship_type = MultiSelectField(choices=REALTIONSHIP_CHOICES, max_choices=1, max_length=19) def save(self, *args, **kwargs): super(UserTrackRelationship, self).save(*args, **kwargs) serializers.py class UserTrackRelSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) user = serializers.PrimaryKeyRelatedField(many=False, read_only=True) track = serializers.PrimaryKeyRelatedField(many=False, read_only=True) class Meta: model = UserTrackRelationship fields = ['id', 'user', 'track', 'relationship_type'] def create(self, validated_data): user_track_serializer = super(UserTrackRelSerializer, self).create(validated_data) user_track_serializer.save() return user_track_serializer views.py class UserTrackRelViewSet(viewsets.ModelViewSet): queryset = UserTrackRelationship.objects.all() serializer_class = UserTrackRelSerializer def perform_create(self, serializer): serializer.save() HTTP request http -a admin:password post http://localhost:8000/user_track/ user=7 track=5 relationship_type="user_watching_track" This is the error that I'm getting and the only data prop that gets validated relationship_type: django.db.utils.IntegrityError: null value in column "track_id" of relation "django_dubplates_usertrackrelationship" violates not-null constraint DETAIL: … -
Method inheritance for DRF views
Consider: class CourseListViewBase(): def list(self, request, format=None): # whatever class CourseListView(generics.ListAPIView, CourseListViewBase): permission_classes = [IsAuthenticated] def list(self, request, format=None): # Why can't I omit this? return CourseListViewBase.list(self, request, format) class CourseListViewGuest(generics.ListAPIView, CourseListViewBase): permission_classes = [] authentication_classes = [] def list(self, request, format=None): # Why can't I omit this? return CourseListViewBase.list(self, request, format) Why do I have to define the list method in the derived classes instead of relying on it being inherited from the base class? If I don't define it, I get a warning like this: AssertionError: 'CourseListViewGuest' should either include a queryset attribute, or override the get_queryset() method. -
My Django/mysql Login dont work, how do i fix it?
I have created a login system for my website which is connected to MySQL Workbench. However, when I test the login feature, it simply takes me to the private page without checking for authentication. I'm not sure what is causing this issue. I will upload images of my code for your review. Thank you for your help! I didnt try that much, i dont find the problem, i compared my code with other peoples login but i dont know why my code doesnt work. -
Is there a way to present the issue and received balance from a customer to the template?
models.py # Customer Model class Customer(models.Model): name =models.CharField(max_length=100) primary_contact = models.CharField(max_length=10) secondary_contact = models.CharField(max_length=10, blank=True) address = models.TextField(blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('customers') # Issue Model class Issue(models.Model): date_time = models.DateTimeField(default=datetime.now) date = models.DateField(auto_now_add = True) customer = models.ForeignKey(Customer, on_delete = models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE, ) quantity = models.PositiveIntegerField() kt = models.IntegerField() rate = models.FloatField() vat = models.IntegerField(default=15) @property def kt_21(self): return round(self.kt / 21 * self.quantity , 2) @property def vat_amt(self): return self.quantity * self.rate * self.vat/100 @property def total_amt(self): return self.quantity * self.rate + self.vat_amt def get_absolute_url(self): return reverse('issue-hist') def __str__(self): return str(self.customer) + " - "+ str(self.total_amt)+' SAR' # Receive Model class Receive(models.Model): date_time = models.DateTimeField(default=datetime.now) date = models.DateField(auto_now_add = True) customer = models.ForeignKey(Customer, on_delete = models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE, ) quantity = models.PositiveIntegerField() kt = models.IntegerField() rate = models.FloatField() vat = models.IntegerField(default=15) @property def kt_21(self): return round(self.kt / 21 * self.quantity , 2) @property def vat_amt(self): return self.quantity * self.rate * self.vat/100 @property def total_amt(self): return self.quantity * self.rate + self.vat_amt def get_absolute_url(self): return reverse('rec-hist') def __str__(self): return str(self.customer) + " - "+ str(self.total_amt)+' SAR' I have these models, now what I want is to present the total quantity issued and … -
Could not parse the remainder after passing a method with attr to Django template
Getting this error Could not parse the remainder: '(module.url)' from 'call_url(module.url)' in Django template calling a method call_url with argument from HTMX request. <p> <span class="fw-semibold">URL:</span> {{ module.url }} <span class="ms-3" hx-get="{{ call_url(module.url) }}" hx-swap="innerHTML">Check URL response</span> </p> I also tried with no square brackets {{ call_url module.url }}, but it did not help Method call_url is passed to context: async def get_project(request, project_id: int): """Detailed project view with modules.""" project = await Project.objects.prefetch_related("modules").aget(pk=project_id) return render( request, "monitor/project.html", context={"project": project, "call_url": call_url}, ) async def call_url(url: str): """Make a request to an external url.""" # TODO: add headers to aiohttp.ClientSession async with aiohttp.ClientSession() as session: async with session.get(url=url) as response: response_code = response.status if response_code == 200: return HttpResponse(content="Page response OK", status=200) else: return HttpResponse( content=f"Error. Response code id {response_code}", status=response_code, ) Tried to pass url directly to async def call_url(url: str = "https://www.google.com"): and call it from template hx-get="{{ call_url }}" but I get an error: Not Found: /project/1/<coroutine object call_url at 0x000001A3A95AA940> [02/May/2023 22:02:02] "GET /project/1/%3Ccoroutine%20object%20call_url%20at%200x000001A3A95AA940%3E HTTP/1.1" 404 3710 What am I doing wrong? -
What is the proper way to use raw sql in Django with params?
Consider that I have a "working" PostgreSQL query - SELECT sum((cart->> 'total_price')::int) as total_price FROM core_foo; I want to use the raw query within Django, and I used the below code to get the result- from django.db import connection with connection.cursor() as cursor: query = """SELECT sum((cart->> 'total_price')::int) as total_price FROM core_foo;""" cursor.execute(query, []) row = cursor.fetchone() print(row) But, I need to make this hard-coded query into a dynamic one with params( maybe, to prevent SQL injections). So, I converted the Django query into - from django.db import connection with connection.cursor() as cursor: query = 'SELECT sum((%(field)s->> %(key)s::int)) as foo FROM core_foo;' kwargs = { 'field': 'cart', 'key': 'total_price', } cursor.execute(query, kwargs) row = cursor.fetchone() print(row) Unfortunately, I'm getting the following error - DataError: invalid input syntax for type integer: "total_price" LINE 1: SELECT sum(('cart'->> 'total_price'::int)) as foo FROM core_... Note that; the field ( here the value is cart) input gets an additional quote symbol during the execution, which doesn't match the syntax. Question What is the proper way to pass kwargs to the cursor.execute(...) with single/double quotes? without single/double quotes? -
How to filter before doing "get_export_formats"
In my admin class, I am able to export information from my Django admin page. However, I am currently working on implementing an additional functionality. Prior to exporting, I would like to apply a filter that only returns information that contains "code". For instance, if I were to select all of my information in the admin, a filter would be applied before exporting, allowing only those files that contain the "code" to be exported. FYI: a user can inform a fund without the code This is my admin class: @admin.register(TrustFund) class TrustFundAdmin(ExportActionMixin, PolymorphicParentModelAdmin): base_model = TrustFund resource_class = TrustFundResource def get_export_formats(self): formats = (base_formats.XLSX,) return [f for f in formats if f().can_export()] This is my resource class: class TrustFundResource(resources.ModelResource): short_name = fields.Field(column_name="Short Name", attribute="short_name") code = fields.Field(column_name="Code", attribute="code") class Meta: model = TrustFund exclude = ( "pkid", ) This is my model class: class TrustFund(UUIDBaseModel, PolymorphicModel): short_name = models.CharField( "Short Name", max_length=255 ) code = models.CharField( "Code", max_length=6, null=True, blank=True, validators=[MinLengthValidator(6)], ) I try to use this code in resource class: def get_queryset(self): # filter And this code in the admin class: def get_export_queryset(self, request): # filter But it does not work. Neither of the two cases -
django.import-export ImportExportMixin customisation
I am using ImportExportMixin to add the import export buttons to my admin page: i write it like this : from django.contrib import admin from .models import * from import_export.admin import ImportExportMixin class PlayerAdmin(ImportExportMixin,admin.ModelAdmin): list_display = [field.name for field in Player._meta.fields] admin.site.register(Player,PlayerAdmin) When I do th export I get something like this : [{"id": 1, "name": "player1", "date_birth": "1997-01-01", "tshirtnumber": 19, "club": 1, "poste": "ST"}] The club is a ForeingKey and I want the name of the club not the id. so what to do ? and please I need the same thing for the import I mean I want to import players with their club name . I am expecting : [{"id": 1, "name": "player1", "date_birth": "1997-01-01", "tshirtnumber": 19, "club": "chelsea", "poste": "ST"}] -
MultiValueDictKeyError at / 'username' //DJango beginners project
strong textI was trying to do CRM on Django tutorial from freecodecamp and completed it but there is an error at the addRecord page for me, which says in terminal Internal Server Error: / Traceback (most recent call last): File "C:\Users\desktop\personaldump\python\django\virt\lib\site-packages\django\utils\datastructures.py", line 84, in getitem list_ = super().getitem(key) KeyError: 'username' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\desktop\personaldump\python\django\virt\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\desktop\personaldump\python\django\virt\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\desktop\personaldump\python\django\virt\Scripts\CRM\first\views.py", line 10, in home username=request.POST['username'] File "C:\Users\desktop\personaldump\python\django\virt\lib\site-packages\django\utils\datastructures.py", line 86, in getitem raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'username' [02/May/2023 23:40:34] "POST / HTTP/1.1" 500 81254 on the server when I try to add record enter image description here return render(request,'home.html',{'records':records}) I tried changing my username from ``` def home(request): records= Record.objects.all() if request.method=='POST': username=request.POST['username'] password=request.POST['password'] user=authenticate(request,username=username, password=password) if user is not None: login(request,user) messages.success(request,"login successful") return redirect('home') else: messages.success(request, "login failed") return redirect('home') return render(request,'home.html',{'records':records}) **to** def home(request): records= Record.objects.all() if request.method=='POST': username=request.POST.get('username') password=request.POST.get('password') user=authenticate(request,username=username, password=password) if user is not None: login(request,user) messages.success(request,"login successful") return redirect('home') else: messages.success(request, "login failed") return redirect('home') ``` if I do that I am directing getting a "login failed" message when Adding … -
Django - Save() will save some fields but not all updated fields
My API receives a remote cURL request with JSON data and saves it to database. It is taking in good values and assigning them to the object but when object.save() is called only a item or 2 is updated in database when 4 items are actually updated. The second part of this is it only happens on the production server but not developers server (runserver) where it runs and saves just fine. In the code, we print each object item after we have set it's new value to verify we have accurate data and fits model requirements. Here is Model class LUMAgentConfig(models.Model): class Meta: unique_together = ('team', 'clientID', 'computerID'), team = models.ForeignKey(Team, related_name='team_lum_agent_config', on_delete=models.CASCADE) clientID = models.CharField(max_length=80) computerID = models.CharField(max_length=80) isEnabled = models.BooleanField(default=False) rebootRequired = models.BooleanField(default=False) lastScanDate = models.DateTimeField(blank=True, null=True) lastUpdate = models.DateTimeField(blank=True, null=True) packageManager = models.CharField(max_length=10, blank=True, default='') packageManagerVersion = models.CharField(max_length=40, blank=True, default='') updateCount = models.IntegerField(default=0) def __str__(self): return str(self.team.id) + " -> Agent -> " + str(self.computerID) Here is our simplest hack of View.py we tried during testing. if validateJSON(myJson): data = json.loads(myJson) computerID = data['computerID'] clientID = data['clientID'] scriptVersion = data['scriptVersion'] packageManager = data['packageManager'] packageManagerVersion = data['packageManagerVersion'] print("computerID - > " + str(computerID)) lumConfig = LUMAgentConfig.objects.get(team_id=team.id, clientID=clientID, … -
SQLAlchemy connection pool - logger.error when pool is full?
In SQLAlchemy's pool, is there a way to get a logger.error call, or to invoke some sort of callback, when a connection is attempted to be made but the pool(+overflow) is already using all of its allocated connections? This is in a web server context - a logger.error would get reported to our Sentry instance, and so we could take action. Note - wanting the request to continue to wait for a connection until its configured timeout. Having a nose around https://docs.sqlalchemy.org/en/20/core/pooling.html, nothing leaps out at me. This is in Django, via https://github.com/altairbow/django-db-connection-pool, and nothing leaps out at me there in its docs or in its source. -
Can't connect to gunicorn server through apache2 - unix domain socket failed
I am using apache2 to try and connect to my django application. I have the django app located in myfolder which I am running from the same location as the manage.py with gunicorn myfolder.wsgi -b unix:/home/user/myfolder/web.sock. From what I can see, this works and is waiting for a connection: [2023-05-02 18:02:10 +0100] [4042470] [INFO] Starting gunicorn 20.0.4 [2023-05-02 18:02:10 +0100] [4042470] [INFO] Listening at: unix:/home/user/myfolder/web.sock (4042470) [2023-05-02 18:02:10 +0100] [4042470] [INFO] Using worker: sync [2023-05-02 18:02:10 +0100] [4042472] [INFO] Booting worker with pid: 4042472 I have my .htaccess file setup with RequestHeader set Host expr=%{HTTP_HOST} RequestHeader set X-Forwarded-For expr=%{REMOTE_ADDR} RequestHeader set X-Forwarded-Proto expr=%{REQUEST_SCHEME} RequestHeader set X-Real-IP expr=%{REMOTE_ADDR} RewriteRule ^(.*)$ unix:/home/user/myfolder/web.sock|http://example.com/$1 [P,NE,L,QSA] but for some reason, when I connect to example.com, I don't get connected to the gunicorn instance. The apache2 logs say [Tue May 02 18:02:28.396785 2023] [proxy:error] [pid 3731828] (111)Connection refused: AH02454: HTTP: attempt to connect to Unix domain socket /home/user/myfolder/web.sock (*) failed [Tue May 02 18:02:28.396907 2023] [proxy_http:error] [pid 3731828] [client xxx.xxx.x.xx:54462] AH01114: HTTP: failed to make connection to backend: httpd-UDS I have confirmed that the web.sock file is created in the target location and I have full permissions over it, so this isn't the same problem as … -
Unable to load my static files in Django production environment
I am deploying my Django application to Railway. I am following this guide, https://docs.djangoproject.com/en/4.2/howto/static-files/deployment/#how-to-deploy-static-files. The app was deployed successfully but cannot load the static files. I followed some online tutorials on this and it is still not working. What did I miss? My Railway deploy log: Not Found: /static/styles/style.css Not Found: /static/images/logo.svg Not Found: /static/styles/style.css Not Found: /static/images/logo.svg Not Found: /static/images/avatar.svg Not Found: /static/images/avatar.svg Not Found: /static/js/script.js Not Found: /static/js/script.js settings.py: DEBUG = False STATIC_ROOT = BASE_DIR / "staticfiles" STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", ] MEDIA_URL = '/images/' MEDIA_ROOT = BASE_DIR / 'static/images' -
How to transfer file from Django server to esp32?
I am working on a project where I have a Django server and an ESP32 with an SD card on it. I want to transfer a .wav file to the ESP32 through HTTP, however, I am not doing it the right way. The file is a little too big for the ESP32 to get, and I get an error, [E][WiFiClient.cpp:517] flush(): fail on fd 48, errno: 11, "No more processes". I've been told that sending the file through JSON was a really bad idea, and I agree. I just don't know how else to send it. I tried this: def text_to_wav(voice_name: str, text: str): language_code = "-".join(voice_name.split("-")[:2]) text_input = tts.SynthesisInput(text=text) voice_params = tts.VoiceSelectionParams( language_code=language_code, name=voice_name ) audio_config = tts.AudioConfig(audio_encoding=tts.AudioEncoding.LINEAR16) client = tts.TextToSpeechClient() response = client.synthesize_speech( input=text_input, voice=voice_params, audio_config=audio_config, ) return b64encode(response.audio_content).decode("utf-8") @api_view(["POST"]) def tts_view(request: Request): voice_name = request.data.get("voice_name") text = request.data.get("text") if not voice_name or not text: print("Missing voice_name or text") return JsonResponse({"error": "Missing voice_name or text"}, status=400) response = HttpResponse(text_to_wav(voice_name, text), content_type="audio/wav") response["Content-Disposition"] = "attachment; filename=%s.wav" % text return response However, I think this is for transferring a file to a web browser, not to an ESP32. On the other hand, I am doing the request like this: void … -
Django webhooks, channels or rest framework
I've three websites - all developed using Python and Django. Let's call them Main, ChildOne and ChildTwo. These sites can be accessed over HTTPS only. I want to be able to create some content on the main site and be able to push this content securely to a child site. I know that I can simply POST data to an endpoint (of a child site). However, I need to make it secure so that only the Main site is able to POST data securely i.e. it doesn't get exploited or altered by any man-in-the-middle attacks or any un-authorised apps. I am bit new to this so trying to learn the best way. Should I use Django Channels over DRF? I've seen payment gateways use webhooks e.g. to post an update about an order. I noticed they send some type of signature which gets verified on the receiver end. How do I create my signature on the main site? Any hints/tips/guidance is appreciated. -
django image preload action - read image geo-metatags
I'm new in Django and this forum. I have a -problem with preload action. I have model: class Observations(models.Model): id = models.IntegerField(primary_key=True) lat = models.CharField(max_length=255, blank=True, null=True) lon = models.CharField(max_length=255, blank=True, null=True) dateandtime = models.DateTimeField(db_column='dateAndTime', blank=True, null=True) # Field name made lowercase. observer = models.ForeignKey('Observers', models.DO_NOTHING, db_column='observer', blank=True, null=True) alpolcode = models.CharField(db_column='alpolCode', max_length=255, blank=True, null=True) # Field name made lowercase. image = models.ImageField(upload_to="images/observations/") and form: class ObservationsForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) dateandtime = forms.DateTimeField( widget=DateTimePicker( options={ 'useCurrent': True, 'collapse': False, }, attrs={ 'append': 'fa fa-calendar', 'icon_toggle': True, } ), ) class Meta: model = Observations fields = [ 'lat', 'lon','dateandtime','observer','alpolcode', 'image'] In the fields lat and lon form store geographic longitude and latitude. I want create action that read before save to database form data read image geolocation metatags (if available of course). Any hint will be helpful. Best regards, Maciej Any hint will be helpful -
How to provide google api credentials for Django app deployed with heroku, using docker
I am deploying my backend Django app using heroku via docker. I am authenticating my flutter front-end api calls to backend using firebase auth. On my local machine, I am storing the google auth json file and referring to those parameters using the following: cred = credentials.Certificate("google_api_data.json") initialize_app(cred) The google_api_data.json file is in the same folder as that of Django project with along with manage.py. I have the json file in gitignore, so I guess that prevents it from being uploaded to heroku while building. Now my questions is: is there a way to store the contents of json file in 'config vars' of heroku and access them? If yes, how will I access them in my local machine? The reason I am confused is, the json file has not just one key-value pair but bunch of lines. Thank you in advance for your help! Following is the json file for reference: { "type": "service_account", "project_id": "xyz", "private_key_id": "xyz", "private_key": "xyz", "client_email": "xyz", "client_id": "xyz", "auth_uri":"xyz", "token_uri": "xyz", "auth_provider_x509_cert_url": "xyz", "client_x509_cert_url": "xyz", } -
Unable to filter datetime field on live server
Hi i am take a record of employe punch in time and punch out time. I Want to filter queryset according to current date Everythings work fine on my local server but it doesn't work on my live server. my Model code is below:- class EmpAttendenceSheet(models.Model): user = models.CharField(max_length=100,verbose_name='user') Employee = models.ForeignKey(EmployeeRegistration,on_delete=models.CASCADE,max_length=150,verbose_name='Employee Name') intime = models.DateTimeField(blank=True,null=True) instate = models.BooleanField(default=False) outtime = models.DateTimeField(blank=True,null=True) outstate = models.BooleanField(default=False) approve = models.BooleanField(default=False) updated = models.DateTimeField(auto_now=True,auto_created=True) my Live server queries are as below:- >>> from attendance.models import EmpAttendenceSheet >>> from django.utils import timezone >>> today = timezone.localtime(timezone.now()) >>> today = timezone.localtime(timezone.now()) >>> attendance = EmpAttendenceSheet.objects.filter(intime__day=today.day,intime__month=today.month,intime__year=today.year) >>> attendance <QuerySet []> I set the timezone in setting.py as TIME_ZONE = 'Asia/Kolkata' -
What does the first line in the "docker-compose.yml" file, that specifies the version mean?
In the first line of the docker-compose.yml file we specify a version: version: '3.9' What exactly does this mean?! After installing the latest version, I tried the following in my Windows 10 cmd: docker-compose --version and the output was: Docker Compose version v2.17.2 so how is it that we type 3.9 in the first line?! -
Python Django - migrate throws django.db.utils.OperationalError: server does not support SSL, but SSL was required
I'm running the following cmd to run the initial migration of django project in my localhost(MAC) and i'm getting the following errors. file "/opt/homebrew/lib/python3.11/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection self.connect() File "/opt/homebrew/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/opt/homebrew/lib/python3.11/site-packages/django/db/backends/base/base.py", line 270, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/homebrew/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/opt/homebrew/lib/python3.11/site-packages/django/db/backends/postgresql/base.py", line 270, in get_new_connection connection = self.Database.connect(**conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/homebrew/lib/python3.11/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ django.db.utils.OperationalError: connection to server at "localhost" (::1), port 5432 failed: server does not support SSL, but SSL was required I'm running the postgresql properly and able to access or connect it using psycopg2. Why it's expecting SSL in my localhost. CMD ran python3 dev.py migrate My database config DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test', 'USER': 'postgres', 'PASSWORD': 'test', 'HOST': '127.0.0.1', 'PORT': '5433', 'CONN_MAX_AGE': 500, 'DISABLE_SERVER_SIDE_CURSORS': True, 'OPTIONS': {'sslmode':'disable'} } } Please let me the root cause of the issue to fix migrations in my local. Thanks I tried directly connecting to the db via psycopg2 -
Django/Docker/pyaudio: pip install failed beaucause of #include "portaudio.h"
I am using Django on Docker with python:3.8.3-alpine image and want to use pyaudio librairy but pip install failed because of portaudio dependency rc/pyaudio/device_api.c:9:10: fatal error: portaudio.h: No such file or directory 9 | #include "portaudio.h" | ^~~~~~~~~~~~~ I've tried many thing like trying to install portaudio before but nothing works maybe comes from my python image but trying python:3.8.3 image is too long to build How to use pyaudio in DJango/Docker project? -
App Version on Graphene GraphQL documentation
It could be a simple question, however I should specify the version I'm already working on my API-gateway. I'm using graphQL with graphene in my django project. I know in a rest-api using django rest framework, on documentation you can specify version Then, it is posible to do it on GraphQl docs?