Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
httpx.ConnectError: [Errno 111] Connection refused
I'm trying to generate api client from my custom api with this package I have generated the api client: openapi-python-client generate --path example_api_client.yaml Built the package with: cd example_api_client/ poetry build -f wheel Copied and installed: pip install ./example_api_client-1.0.0-py3-none-any.whl But when i try to do a request throw the error: httpx.ConnectError: [Errno 111] Connection refused The script is Django custom command: from example_api_client.api.authentication import authentication_user_list from example_api_client.models.user import User from example_api_client.client import Client class Command(BaseCommand): def handle(self, *args, **kwargs): BASE_URL = 'http://0.0.0.0:8002' client = Client(base_url=BASE_URL, verify_ssl=False, raise_on_unexpected_status=True) response: User = authentication_user_list.sync(client=client) Anybody could help me please ? Thanks in advance. -
Python Django Rest Framework serializer to representation, can I return list of Ordered dicts into one dict, ex., return data in one curly brackets?
I have a task where I need to combine the data of multiple serializers into one level and return all the data in one json array. The problem I encountered is that the data keys are the same but values change so I am stuck in how to remove the curly brackets, but don't change the data. For example my code looks like: serializers.py class OneSerializer(serializers.ModelSerializer): spec = DifferentSerializer(many=True) service = Different2Serializer(many=True) class Meta: model = models.SomeModel def to_representation(self, instance): data = super(OneSerializer, self).to_representation(instance) for s in data['spec']: s.update({"form": instance.form}) s.move_to_end('form', last=False) for s in data['spec']: s.update({"appointment": instance.appointment}) s.move_to_end('appointment', last=False) for s in data['spec']: s.update({"d_appointment": instance.d_appointment}) s.move_to_end('d_appointment', last=False) for s in data['spec']: s['service'] = data['service'] data.pop('service') specialist = data.pop('spec') return specialist I have removed most of code but the principle is I combine data of other serializers into one and using data.pop, I get the data in one level. The return looks like this: [ { "form": null, "appointment": false, "d_appointment": false, "service": [] } ], [ { "form": null, "appointment": false, "d_appointment": true, "service": [] } ], [ { "form": null, "appointment": true, "d_appointment": false, "service": [] } ], Which returns data correctly except for the fact that each … -
Django & JQuery: Submit button is not working after JQuery replaceWith a html file
I have a formset where users can save the data in forms 1 at a time, with an overall Submit button at the bottom, which is disabled. When all forms within the formset are saved, I want to make the overall Submit button not disabled. Each form save button sends an AJAX request, which replaces some of my HTML divs, including one with the button. The replace works, the button is updated and not disabled, however it does not work. I have also tried using jquery html instead of replaceWith but it results in the same thing Here's my code: formset.html {% for form in formset %} <thead> <th>Header 1</th> <th>Header 2</th> </thead> <tr> <td>{{form.instance}}</td> <td> <div class='btn-group mr-1 mb-1'> <button id='{{ form.instance.id }}-save-button' action="{% url 'results:save_variant_class' %}" type='button' class="btn btn-warning save-variant-classification" value='Save' </div> </td> </tr> {% endfor %} </table> {% include "analyse_sample_button.html" %} analyse_sample_button.html {% if stuff_to_do %} <button type="submit" name="submit" value="Analyse sample" class="btn btn-danger float-right" disabled>There are forms to for this sample</button> {% else %} <button type="submit" name="submit" value="Analyse sample" class="btn btn-success float-right">Analyse sample</button> {% endif %} views.py def save_variant_class(request, **kwargs): data = dict() if request.method == 'POST' and request.is_ajax(): obj = MyModel.objects.get(id=request.POST['id']) form = VCForm(data=request.POST, instance=obj) if … -
How do I delete the django cache database table?
I have been using django's database caching as shown here: https://docs.djangoproject.com/en/4.1/topics/cache/#database-caching Recently I have migrated to redis caching, but I still have the cache table in my database from the command python manage.py createcachetable. How can I safely delete this table? -
How to ,centralize deselect search box in django crispy form
I created a searchable dropdown box in django with crispy forms using dselect() like so: form.html {% extends 'layout.html' %} {% load crispy_forms_tags %} {% block content %} <div class="container"> <div class="row justify-content-center"> <div class="col-8"> <h1 class="mt-2">Form for Update</h1> <hr class="mt-0 mb-4"> <form method="POST" enctype="multipart/form-data"> <!-- Security token --> {% csrf_token %} <!-- Using the formset --> {{ form |crispy}} <button type="submit" class="btn btn-primary">Submit</button> </form> </div> </div> </div> <script> dselect(document.querySelector('#id_app'), { search: true }); </script> {% endblock %} But the problem is that the resulting searchbox is not centralized, the searchbox comes to the lower left corner. It ends up like so: And I want something more like this: Does anyone know how to change that ? -
how to register django_migrations table to django-admin panel
how to add or register django_migrations table or MigrationRecorder model to django-admin panel? I have tried the following solutions, but to no avail! from django.db.migrations.recorder MigrationRecorder from django.contrib import admin admin.site.register(MigrationRecorder) from django.db.migrations.recorder MigrationRecorder from django.contrib import admin admin.site.register(MigrationRecorder.Migration) -
Django - Add extra clause for login with AbstractUser inheritance
I have the following model: employee.py class Employee(auth_models.AbstractUser, MetadataModel): user = models.CharField(unique=True, primary_key=True) first_name = models.CharField(blank=True, null=True) last_name = models.CharField(blank=True, null=True) is_deleted = models.BooleanField(default=False) My settings.py references to Employee model for authentification: AUTH_USER_MODEL = 'core.Person' By default, the user can only log in with the AbstractUser model when is_active=True. How can I change this condition so that the authentification is: is_active==True and is_deleted==False preserving the inheritance on AbstractUser in Employee? -
Python Django embedding static tags inside strings
Want to generate a dynamic HTML code as python string with some embedded images as shown in the following django code. This code is supposed to be added to another existing HTML file with load static header. def printFollowups(self): return """ <table> <tr> <td> <p><strong> Hello World </strong></p> </td> <td> <img src="{% static 'images/logo.png' %}" align="right"> </td> </tr> </table>""" But, the problem is that image is not rendered on a page. May be problem with the quotes. Want to know how to embed django static tags inside the python string. Tried with different quotes and concatenation. -
What are some good practices of storing image with Django Backend?
Background: Assume for each Person class, there's only a single profile picture associated with it I understand that one way to achieve this is to have a ImageField in the Person's models.py file, and have the profile picture being uploaded to the /media/ directory in my django project But, hypothetically, if I could have thousands (or maybe even millions) of users, would this still be a good solution? An alternative way I heard is to store the image in S3, and only link the image url in Person's models.py file, would this be more suitable (faster read, cheaper storage, etc.) for my use case? Thanks! -
Django warnings (Make sure every static file has a unique path)
What is the reason for this warnings? I get them during docker-compose up command. Found another file with the destination path 'admin/js/vendor/jquery/LICENSE.txt'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. Found another file with the destination path 'admin/img/LICENSE'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. My INSTALLED_APPS in settings.py looks like: INSTALLED_APPS = [ "adminlte3", "adminlte3_theme", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "rest_framework", "corsheaders", "django_extensions", "drf_standardized_errors", "user", "celery", ] Statics: PROJECT_ROOT = os.getcwd() STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, "static") -
How use ProcessPoolExecutor in django?
In a Django Project I want to use ProcessPoolExecutor but I can do that. Is there any solution? I call a function in view that has executor. I use Django==4.1.7. what should add to my function to run in django. The start() function works properly outside django. but doesn't work in django. from a views.py in django app call a function that contain executor: def start(): #'... some code here' with concurrent.futures.ProcessPoolExecutor(max_workers=num_procs) as executor: -
Encountered error while trying to install package. ╰─> pycrypto [closed]
I am trying to install django-encrypted-fields by the following command pip install django-encrypted-fields but I can not install it becouse of the following error # include <gmp.h> ^~~~~~~ 1 error generated. error: command '/usr/bin/clang' failed with exit code 1 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: legacy-install-failure × Encountered error while trying to install package. ╰─> pycrypto note: This is an issue with the package mentioned above, not pip. hint: See above for output from the failure. I am using Python 3.10.9 on mac any help?? -
Django Channels and Signals
i am new with django and django channels i wanna create app and use signals when a user insert new row in pending order table i send signal to Django channels after save record in real-time My application have more than one company so i need filter users only users in the same company see the signal or the event of creating new pending order of the same company any new order or row can filter by column company to send signal to users of the same company only , May like group every users of the same company and sent to them notification to know there is new pending order any suggestion how can i make it in easy and efficient way Thank a lot code may look like that models.py from django.db import models from django.utils.timezone import now from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import User class Order(models.Model): pass class PenddingOrder(models.Mode): status = models.CharField(max_length=15,unique=True) date = models.DateField(default=now) order = models.ForeignKey( Order,models.CASCADE) company = models.CharField(max_length=15,unique=True) class CompanyUsers(models.Model): user = models.ForeignKey( User,models.CASCADE) company = models.CharField(max_length=15,unique=True) # method for sent signal or notification to channels @receiver(post_save, sender) def pendingOrderPostSave(sender, instance, **kwargs): pass Consumers.py from channels.generic.websocket import WebsocketConsumer … -
Django migration giving Mysql Syntex error on making table
I am running migrate command and receiving error django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ', 4) NULL, `stats_type` varchar(50) NULL, `created_at` datetime(6) NULL, `update' at line 1") My Django Model is: class TopStats(models.Model): module_id=IntegerField(default=None, null=True) module_name=CharField(max_length=50, null=True,blank=True,default=None) object_type=CharField(max_length=50, null=True, blank=True, default=None) count_type=CharField(max_length=50, null=True, default=None) stats_type=CharField(max_length=50, null=True, blank=True,default=None) top_values= DecimalField(max_digits=11, decimal_places=4,default=None, null=True) created_at= DateTimeField(auto_now_add=True, blank=True, null=True) updated_at= DateTimeField(auto_now=True, blank=True, null=True) class Meta: db_table = "track_stats" i searched on this platform this question 1 question 2 and so on but that not worked for me, updating mysql is not a option, i just want to make table yet, will work on serialzer in future. django details are asgiref==3.6.0 djangorestframework==3.14.0 sqlparse==0.4.3 djangorestframework-simplejwt==5.2.2 mysqlclient==2.1.1 django-environ==0.9.0 django-cors-headers==3.13.0 requests==2.26.0 and Python is 3.10.9 other question is that, it made a lot of migrations because i was changing and check error againg and again, should i delete all migrations?i also hace other tables migrations, but right now only this model is creating problem from last 7 days. -
Seemingly random PostgreSQL connection drops while handling Django requests
For the past few days, our Django website has been experiencing random PostgreSQL connection drops that would raise InterfaceError: connection already closed in random locations. The queries that cause the error occur in different views at random and we can't replicate the issue reliably. It occurs very frequently, somewhere between 1-10% of requests that make DB queries. All stack traces follow the same pattern. The only thing that differs is the location of our query that caused it. Here is an example stack trace. InterfaceError: connection already closed File "django/db/backends/base/base.py", line 301, in _cursor return self._prepare_cursor(self.create_cursor(name)) File "django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "django/db/backends/postgresql/base.py", line 269, in create_cursor cursor = self.connection.cursor() InterfaceError: connection already closed File "django/core/handlers/exception.py", line 56, in inner response = get_response(request) File "django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "contextlib.py", line 79, in inner return func(*args, **kwds) File "django/views/generic/base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "django/contrib/auth/mixins.py", line 73, in dispatch return super().dispatch(request, *args, **kwargs) File "django/views/generic/base.py", line 142, in dispatch return handler(request, *args, **kwargs) File "tolink/views/app.py", line 273, in get self.set_profile(pk) File "tolink/views/app.py", line 267, in set_profile profile = Profile.objects.filter(pk=pk, user=self.request.user).first() File "django/db/models/query.py", line 1047, in first … -
Django template block item in condition if/else
I have this code in layout.html {% block createListing %}{% endblock %} {% block listingPage %}{% endblock %} {% block activeListings %}{% endblock %} {% block watchlist %}{% endblock %} {% block Categories %}{% endblock %} Need conditional using block in index.html {% if page == "CreateListing" %} {% block createListing %} <h2>Create Listing</h2> TODO {% endblock %} {% elif page == "ActiveListings"%} {% block activeListings %} <h2>Active Listings</h2> TODO {% endblock %} {% endif %} Here's the thing - even with the page flag condition set to False - the block on the page still rendered!!! It seems that the block declaration ignores/overrides the outer if statement. I don't know about you, but that was not what I expected. I want use: (in layout.html) {% block body %}{% endblock %} And (in 'index.html`) {% if page == "CreateListing" %} {% block body %} <h2>Create Listing</h2> TODO {% endblock %} {% elif page == "ActiveListings"%} {% block body %} <h2>Active Listings</h2> TODO {% endblock %} {% endif %} And so on... -
how can I show multiple objects of a multiple objects using django ORM?
if co is None: try: address = **Contract**.objects.filter(address= servicesearch) print(address) except Contract.DoesNotExist: address= None for add in address: co = add.contractservices_set.all() print(co) the first query yields <QuerySet [<Contract: Contract object (52)>, <Contract: Contract object (55)>]> the second query yields <QuerySet [<Contractservices: Contractservices object (88)>, <Contractservices: Contractservices object (89)>, <Contractservices: Contractservices object (90)>, <Contractservices: Contractservices object (91)>]> <QuerySet [<Contractservices: Contractservices object (98)>, <Contractservices: Contractservices object (101)>, <Contractservices: Contractservices object (102)>, <Contractservices: Contractservices object (99)>, <Contractservices: Contractservices object (103)>, <Contractservices: Contractservices object (100)>, <Contractservices: Contractservices object (104)>]> All Good.... However, when I am trying to render the results its only showing the **contract **objects of 55. I want to show both **contract **objects 52 and 55. please help... my paginator view is.. paginator = Paginator(co,8) if request.GET.get('page') == None: page_number = 1 else: page_number =request.GET.get('page') DataFinal=paginator.get_page(page_number) totalpage =DataFinal.paginator.num_pages I cant change the template as it is just one search criteria among many.. your text -
The right way to include Vue 3 into Django 4 project so it will not cause troubles during deployment as one at a single server?
i am still pretty new to the Django and especially to the Vue js (and everything that have 'js' in it). I have a simple Django 4.1.4 project with modern requirements to it performance (no reloading, basically). i have to build both sides of the site, and to give you some context i will describe my problem and how i tried to solve it. Hopefully this will help to understand why i obligated to use Vue. (Please tell me if i am mistaken and it can be easily solved without additional framework): I had a table that shows all the qs(queryset) items in a table. I need to show them in a template so user can filter, paginate and sometimes update them without page reloading. I made all of this with JQuery (excluding objects updating), and this looks and feels disgusting compared to everything i've done before. Just look at this example of handling a response and building table's row x_x $.each(response["data"], function (a, b) { row = "<tr class='trow'> <td class='td-content-cut'><span>" + b.product + "</span></td>" + "<td><span class='td-content centered ps-2'>" + ((b.mp == 'WB') ? wbIcon : ((b.mp== 'OZ') ? ozIcon : ((b.mp == 'YM') ? ymIcon : '-'))) … -
Filtering on many to many field in the child model from parent model is too slow in Django
I have a query where I get a list of org_id, city, pincode and I want parents name field(which can be multiple). I have tried with the below queries and I am able to achieve it. But the performance of the query is too slow. Can anyone improve my queries for better speed or if you have any other approach to tackle the problem is much appreciated. class Parent(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=125, blank=True, null=True, db_index=True) class RelatedModel(models.Model): org_name = models.CharField(max_length=125, blank=True, null=True, db_index=True) city = models.CharField(max_length=125, blank=True, null=True, db_index=True) pincode = models.CharField(max_length=125, blank=True, null=True, db_index=True) class Meta: unique_together = ('org_name', 'city', 'pincode') class Child(models.Model): parent = models.OneToOneField(Parent, on_delete = models.CASCADE, related_name='child_parent') tags = models.ManyToManyField(RelatedModel, blank=True, related_name='tags_relatedmodel') Input data: data = [{"org_name":"Samaritan", "city":"Delhi", "pincode":"500800"},{"org_name":"Whitefield", "city":"Bengaluru"}] Query: query_fields = Q() for i in data: if i.pincode == "" or i.pincode == None: query_fields = query_fields | Q(tags__org_name=i.org_name, tags__city=i.city) else: query_fields = query_fields | Q(tags__org_name=i.org_name, tags__city=i.city, tags__pincode=i.pincode) queryset = Child.objects.prefetch_related('tags').filter(parent=OuterRef('id') ).filter(query_fields).order_by('parent_id').distinct('parent_id',).values('parent',) result = Parent.objects.filter(id__in=Subquery(queryset)).order_by('-name') This query is taking almost 1min 10seconds to query 200000 records -
Django adminlte3 can't load Bootstrap
I have a Django app and I want to use AdminLTE3. But I have a problem with Bootstrap loading. My settings.py STATIC_URL = "/static/" STATIC_ROOT = '/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) What is the problem? Logs are: 2023-02-22 07:41:01,830 WARNING django.request [/usr/local/lib/python3.10/site-packages/django/utils/log.py:224] Not Found: /static/admin-lte/dist/js/adminlte.min.js -
Why converting Django website to PWA causes error
I am trying to run my website made in Django as PWA. I did everything according to https://www.geeksforgeeks.org/make-pwa-of-a-django-project/ (+ added images directory with required images) and this is the result Have you got any ideas what I am doing wrong? -
Django celery tasks are creating the queue but the orm operations are not being executed
I am trying to create tasks for adding data to 5 different tables by using celery and Azure ServiceBus as my broker. The tasks are received and are in queue but the operations are not executed. ==== views.py ==== enter image description here ==== tasks.py ==== enter image description here ==== settings.py ==== Celery settings enter image description here ==== celery worker logs ==== [2023-02-22 07:15:41,413: ERROR/MainProcess] Task handler raised error: TypeError('no default __reduce__ due to non-trivial __cinit__') Traceback (most recent call last): File "/home/bala/Desktop/zeron-backend/venv/lib/python3.10/site-packages/billiard/pool.py", line 596, in body put(task) File "/home/bala/Desktop/zeron-backend/venv/lib/python3.10/site-packages/billiard/connection.py", line 233, in send self._send_bytes(ForkingPickler.dumps(obj)) File "/home/bala/Desktop/zeron-backend/venv/lib/python3.10/site-packages/billiard/reduction.py", line 56, in dumps cls(buf, protocol).dump(obj) File "stringsource", line 2, in uamqp.c_uamqp.CompositeValue.__reduce_cython__ TypeError: no default __reduce__ due to non-trivial __cinit__ [2023-02-22 07:15:42,084: ERROR/MainProcess] Task handler raised error: TypeError('no default __reduce__ due to non-trivial __cinit__') Traceback (most recent call last): File "/home/bala/Desktop/zeron-backend/venv/lib/python3.10/site-packages/billiard/pool.py", line 596, in body put(task) File "/home/bala/Desktop/zeron-backend/venv/lib/python3.10/site-packages/billiard/connection.py", line 233, in send self._send_bytes(ForkingPickler.dumps(obj)) File "/home/bala/Desktop/zeron-backend/venv/lib/python3.10/site-packages/billiard/reduction.py", line 56, in dumps cls(buf, protocol).dump(obj) File "stringsource", line 2, in uamqp.c_uamqp.CompositeValue.__reduce_cython__ TypeError: no default __reduce__ due to non-trivial __cinit__ [2023-02-22 07:15:43,135: ERROR/MainProcess] Task handler raised error: TypeError('no default __reduce__ due to non-trivial __cinit__') Traceback (most recent call last): File "/home/bala/Desktop/zeron-backend/venv/lib/python3.10/site-packages/billiard/pool.py", line 596, in body put(task) … -
Hidden checkbox status "1" does not save in database in Django app
In my app I have a hidden checkbox field which I intend to mark checked depending on some condition at runtime. I have tried various ways to hide the checkbox: In forms.py using: 'checkbox_field': forms.HiddenInput() Or in the template: Using {{ checkbox_field.as_hidden }} And the checkbox_field is not displayed as expected. However the problem I am facing is that the checkbox's status ('1' for True) is not saved on form submit. Whereas if I do not hide the checkbox the value is saved. As a work around (on the other hand), if I keep the checkbox visible, mark it True and then set it as hidden (at runtime), the value is saved. It's obvious I am getting something wrong here. My question is: How may I keep the checkbox hidden and at the same time be able to save its status in the database? -
How to handle error depending on error type?
I have a django view with two excpetions class CreateUser(APIView): queryset = User.objects.all() def post(self, request): avi_pic = request.data.get('avi_pic') username = request.data.get('username') print(avi_pic) try: user = User.objects.get(username=username) return Response({'error': 'Username is already taken.'}, status=status.HTTP_400_BAD_REQUEST) except User.DoesNotExist: user = User.objects.create(avi_pic=avi_pic, username=username) user.save() serializer = UserRegisterSerializer(user) return Response(serializer.data, status=status.HTTP_201_CREATED) except: return Response({'error': 'An unexpected error occurred.'}, status=500) in my React Native frontend i want to dispatch error based on the type of error but can't seem to make it work. const completeSignUp = dispatch => async data => { const formData = new FormData(); const username = data.user_name; formData.append('avi_pic', { uri: data.avi_pic, type: 'image/jpeg', name: data.avi_pic, }); formData.append('username', username.toLowerCase()); try { await axios.post(`${BACKEND_URL}/register/`, formData, { headers: { 'Content-Type': 'application/json', }, }).then(res => { if (res.status === 200){ const response = res.data; RNSInfo.setItem('user', 'true', {}); dispatch({ type: 'signin', user: 'true', }); } }); } catch (error) { if (error.response && error.response.data === 'Username is already taken.') { dispatch({ type: 'username_error', error: 'This username is already taken. Please choose a different one.', }); } else { dispatch({ type: 'error_1', payload: 'Something went wrong. Please try again.', }); } } }; It's only dispatching the 'error_1' Is there a better approach to this? -
I need to get the unique values from the tags field
my sample record in my mongoid: [ { "name": "name1", "status": "one", "unit": [ ], "child": [], "element": [ "6604" ], "tags": [ "tag1", "tag2", "tag3" ] }, { "name": "name2", "status": "one", "unit": [ ], "child": [], "element": [ "6604" ], "tags": [ "tag1", "tag2", "tag3", "tag4" ] } ] i tried in this way to get tagsdata = dbname.distinct('tags.values') expecting the output "tag1","tag2","tag3","tag4" like all unique values form the key field