Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pytest tests only one case with @pytest.mark.parametrize
I defined UserFactory class in tests/factories.py as shown below following the doc. *I use pytest-django and pytest-factoryboy in Django: # "tests/factories.py" import factory from django.contrib.auth.models import User class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User And, I defined test_user_instance() with @pytest.mark.parametrize() to test 4 users as shown below: # "tests/test_ex1.py" import pytest from django.contrib.auth.models import User @pytest.mark.parametrize( "username, email", { ("John", "test@test.com"), # Here ("John", "test@test.com"), # Here ("John", "test@test.com"), # Here ("John", "test@test.com") # Here } ) def test_user_instance( db, user_factory, username, email ): user_factory( username=username, email=email ) item = User.objects.all().count() assert item == True But, only one user was tested as shown below: $ pytest -q . [100%] 1 passed in 0.65s So, how can I test 4 tests? -
Profile not creating when creating a User with Django
I'm using DRF for my project and I need help in automatically creating a Profile instance for a User model when a User is created. My signals is: from django.db.models.signals import post_save from django.conf import settings from django.contrib.auth import get_user_model from .models import Profile User = get_user_model() def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) post_save.connect(create_user_profile, sender=User) -
Django With Clean Architecture
I'm trying to build a python application using Clean Architecture principles. I already have the following structure: app/ ├── src │ ├── dependencies │ │ ├── dependencies.py │ │ └── __init__.py │ ├── infrastructure │ │ └── ui │ │ ├── __init__.py │ │ ├── interfaces │ │ │ ├── __init__.py │ │ │ └── ui.py │ │ ├── desktop │ │ │ ├── __init__.py │ │ │ └── tkinter_ui.py │ │ └── web │ │ ├── flask_ui │ │ │ ├── constants │ │ │ │ ├── constants.py │ │ │ │ └── __init__.py │ │ │ ├── endpoints │ │ │ │ ├── endpoints.py │ │ │ │ └── __init__.py │ │ │ ├── flask_ui.py │ │ │ └── __init__.py │ │ └── __init__.py │ ├── __init__.py │ └── main.py Makefile And it works fine for both Tkinter and Flask. Now I'm considering adding django to my project, so I thought my structure would be something like this: app/ ├── src │ ├── dependencies │ │ ├── dependencies.py │ │ └── __init__.py │ ├── infrastructure │ │ └── ui │ │ ├── __init__.py │ │ ├── interfaces │ │ │ ├── __init__.py │ │ │ └── ui.py │ … -
Django: Create and Update seperate objects
In Django models, I aim to ensure that when I create an object from one class, the corresponding object is created in another class. Furthermore, certain fields should be automatically inherited. Here's an example: `class Model1(models.Model): Malfunction = models.CharField(max_length=255, null=True) def __str__(self): return self.Malfunction class Model2(models.Model): sit_id = models.AutoField(primary_key=True) given_Malfunctions = models.ManyToManyField(Model1, blank=True) dynamik_2 = models.CharField(max_length=255, default=None, blank=True) def __str__(self): return f"[{self.sit_id:02d}]" class Model3(models.Model): connection_to_model2 = models.ForeignKey(Model2, on_delete=models.CASCADE, default=None) dynamik_3 = models.CharField(max_length=255, default=None, blank=True) ` Model3 object should be created every time a Model2 object got created. And the fields from dynamik_2 should be automatically updated to dynamik_3. Should i define the signals or functions in model 3? I encountered an issue with "post_save" since I couldn't establish the connection between related objects. -
User Validation Errors in XML File Uploading: Python/Django
When trying to create functionality in a full stack Django/React project that allows a user to upload (specifically XML) files, I ran into an issue in my User validation where it's throwing errors that the userId is not being grabbed. Here are the following relevant files: [ { "model": "easapi.user", "pk": 1, "fields": { "uid": "123456", "name": "Hayley", "email": "anemail@g.com" } } ] [ { "model": "easapi.log", "pk": 1, "fields": { "user": 1, "dateStart": "2022-11-22", "dateEnd": "2022-11-22", "dateGenerated": "2022-11-22" } } class User(models.Model): uid = models.CharField(max_length=50) name = models.CharField(max_length=50) email = models.EmailField(max_length=75) def __str__(self): return self.name class Log(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) dateStart = models.DateTimeField(max_length=20) dateEnd = models.DateTimeField(max_length=20) dateGenerated = models.DateTimeField(max_length=20) log_hash = models.CharField(max_length=255) def __str__(self): return self.name class LogView(ViewSet): def retrieve(self, request, pk): log = Log.objects.get(pk=pk) serializer = LogSerializer(log) return Response(serializer.data) def list(self, request): logs = Log.objects.all() uid_query = request.query_params.get('uid', None) if uid_query is not None: logs = logs.filter(user=uid_query) serializer = LogSerializer(logs, many = True) return Response(serializer.data) @staticmethod def generate_unique_log_hash(user_uid): while True: # Combine user UID, current timestamp, and random seed unique_string = f"{user_uid}_{int(time.time())}" # Generate a hash using SHA-256 hash_object = hashlib.sha256(unique_string.encode()) unique_hash = hash_object.hexdigest() try: # Attempt to retrieve a log with this hash Log.objects.get(log_hash=unique_hash) except Log.DoesNotExist: … -
App TemplateDoesNotExist in Django Project
I am struggling to figure out why I am receiving the TemplateDoesNotExist error in my project. This is my initial project layout. The project name is localassets, the initial app name is assetlist. I have registered the app in my settings.py file. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'assetlist.apps.AssetlistConfig', 'django_tables2', 'django_filters', 'widget_tweaks', 'django_bootstrap_icons', 'django_extensions', 'crispy_forms', 'crispy_bootstrap4', ] 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', ] ROOT_URLCONF = 'localassets.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I have successfully created views and templates within this app and it displays all templates without issues. I now want to add another app to this project. This app is named workorders. I created the app the folder structure is shown below: I have also registered this app in the project settings.py file. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'assetlist.apps.AssetlistConfig', 'django_tables2', 'django_filters', 'widget_tweaks', 'django_bootstrap_icons', 'django_extensions', 'crispy_forms', 'crispy_bootstrap4', 'workorders.apps.WorkordersConfig', ] 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', ] ROOT_URLCONF = 'localassets.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', … -
Django: How to autocomplete user-creator field of a model in admin-panel
class Post(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) text = models.TextField() approved = models.BooleanField(default=False) total_media_count = models.PositiveIntegerField(default=0) group = models.ForeignKey('bot_users.BotUserGroup', on_delete=models.SET_NULL, null=True, blank=True) I log in in admin-panel (as a superuser, as a staff. Doesn't matter) and I want user field to be autocompleted with user who made this POST model instance in admin-panel. How can I do that? I've tried save() method, but it doesn't work for me. Also save_model method in admin.py P.S. Function of making posts in the project can only be made from admin-panel -
Celery: No result backend is configured
I am trying to use Celery to asynchronously webscrape course registration info from a school university website. Ultimately, I want to build something where users are notified if a seat opens up in a specific course. RabbitMQ is my message broker. I am using Django, when running my server I am met with an error. I don't know what I am missing but this is my first project using something like celery to query data asynchronously. If someone could be show me what i'm missing that would be greatly appreciated. Below is a screenshot of my RabbitMQ dashboard which I believe is running and configured with my project. Below is my code settings CELERY_BROKER_URL = 'amqp://localhost:5672' # RabbitMQ broker URL CELERY_RESULT_BACKEND = 'amqp://localhost:5672' views.py from django.shortcuts import render from bs4 import BeautifulSoup import requests from .forms import CourseRegistrationForm from .tasks import scrape_course_data def main(request): form = CourseRegistrationForm() if request.method == 'POST': form = CourseRegistrationForm(request.POST) if form.is_valid(): term = form.cleaned_data['semester'] subj = form.cleaned_data['subject'] crse = form.cleaned_data['course_number'] classes_result = scrape_course_data.delay(term, subj, crse) classes = classes_result.get() # Get the actual result print(classes) context = { 'form': form, 'classes':classes } return render(request, 'classes.html', context) else: form = CourseRegistrationForm() context = { 'form': form, } … -
Submitting jobs (to a postgre database) through django webpage, using slurm
I'm looking for advice on how to proceed, assuming at all this could be a viable course of action. I have coded a web-based interface (Django) to access some data stored on (an external) database. The role of the webpage is to serve as GUI to show the user what data can be downloaded, and where they are on a map. To avoid overwhelming the machine hosting the database, I am thinking in putting an intermediate layer between Django and the database, to manage submission of request to extract data. That would be slurm (or torque). It needs to be able to communicate through some python API. In essence, what I want to achieve is to allow the user to download data via either gui (Django amd plotly), OR by submitting a job file to slurm. The manager will, in turn, queue all the jobs and extract them one at the time. As an expected result, each registered user on the Django page, could access a dashboard (plugged to slurm) showing which jobs are running/pending, how long to completion, and possibly purge the ones that have already completed (or are no longer wanted). Note: I have only a few months … -
dotenv can not load read.dotenv
I have a django application. And I have dockerized the app. But I have a problem with the django-dotenv package. I have installed the django-dotenv package and not the python-dotenv. But if I try on my local machine: dotenv.read_dotenv() I get this error: Module 'dotenv' has no 'read_dotenv' member So I checked with pip freeze in my virtual environment if I have installed the correct package: (env) PS C:\repos\DWL_backend> pip freeze asgiref==3.6.0 attrs==23.1.0 certifi==2022.12.7 cffi==1.15.1 charset-normalizer==3.0.1 cryptography==39.0.0 defusedxml==0.7.1 Django==4.1.6 django-allauth==0.52.0 django-cors-headers==3.13.0 django-dotenv==1.4.2 djangorestframework==3.14.0 drf-spectacular==0.26.2 idna==3.4 inflection==0.5.1 jsonschema==4.17.3 oauthlib==3.2.2 Pillow==9.4.0 psycopg2==2.9.6 pycparser==2.21 PyJWT==2.6.0 pyrsistent==0.19.3 python3-openid==3.2.0 pytz==2022.7.1 PyYAML==6.0 requests==2.28.2 requests-oauthlib==1.3.1 sqlparse==0.4.3 tzdata==2022.7 uritemplate==4.1.1 urllib3==1.26.14 And now the funny part. I can run docker with: dotenv.read_dotenv() And the requirements.txt looks like: Django>=4.0.4 djangorestframework>=3.13.1 psycopg2>=2.9.3 drf-spectacular>=0.22.1 Pillow>=9.1.0 drf-yasg==1.20.0 django-cors-headers==3.10.1 django-dotenv So the package name django-dotenv are the same. oke. when I do a uninstall. I see this two packages: Found existing installation: django-dotenv 1.4.2 Uninstalling django-dotenv-1.4.2: Would remove: c:\repos\dierenwelzijn_backend\env\lib\site-packages\django_dotenv-1.4.2.dist-info\* c:\repos\dierenwelzijn_backend\env\lib\site-packages\dotenv.py what is dotenv.py? And I have read the official documentation: https://github.com/jpadilla/django-dotenv Question: how to run dotenv.read_dotenv on my localhost? -
How can we use Django property decorator in Django rest framework?
Hello I trying to use Django property decorator in Django rest framework here my code Model.py class TempCalculate(models.Model): items = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField() create_at = models.DateField(auto_now_add=True) create_by = models.ForeignKey(User, on_delete=models.CASCADE) @property def Price(self): self.price = (PriceMaster.objects.get(items = self.items)) * self.quantity Serializer.py from rest_framework import serializers from base.models import TempCalculate class TempCalSerializer(serializers.ModelSerializer): class Meta: model = TempCalculate fields = "__all__" api/view.py @api_view(['GET']) def TempItem(request): queryset = TempCalculate.objects.all() serializer_class = TempCalSerializer(queryset, many=True) return Response(serializer_class.data) **I trying to access self.price (which I have make property decorator in models.py) in rest api ** -
Django - working example of graphene aiodataloader
I've been looking into using a DataLoader in Django to optimise Graphene resolvers. I have been having trouble finding a working example of this as it requires multi threading. Based on what I can tell, there is no longer a way to specify executors in the latest versions of GraphQL in python. Does anyone have a working setup as an example? I was following the example below, and everytime I use async for my resolvers, I get: RuntimeError: There is no current event loop in thread 'ThreadPoolExecutor-1_0'. Which I think makes sense because GraphQL is using a sync executor by default (I stand corrected). I got this example from: https://docs.graphene-python.org/en/latest/execution/dataloader/ -
Django - 403 error while accessing static files in ec2 ubuntu server with nginx
I have used nginx default port 80. Deployed successfully django app. But got 403 error while accessing static files.. I know it is permission related issue. So I tried all the ways. but nothing is workout. gave 777 permission and www-data user. still I got permission denied error. file path structure location /static/ { root /home/ubuntu/FunQuiz-backend/FunQuizAPI/staticfiles/; autoindex on; } -
Is there any way to relay the data(stud.id) to the POST form?
{% for stud in student %} <tr> <td class="text-center">{{stud.id}}</td> <td class="text-center">{{stud.name}}</td> {% if x %} <td class="text-center">{{stud.main_sub}}</td> <td class="text-center">{{stud.fourth_sub}}</td> {% endif %} <td class="text-center"> <div> <a class="btn btn-outline-primary rounded " href="{% url 'updatestudent' stud.id %}" style="width: 0.75in;"> Edit </a> <button type="button" class="btn btn-outline-danger" data-bs-toggle="modal" data-bs-target="#exampleModal" style="width: 0.75in;"> Delete </button> </div> </td> </tr> {% endfor %} </tbody> </table> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="exampleModalLabel">Confirmation</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> Are you sure want to delete? {{stud.id}} </div> <div class="modal-footer"> <form action="" method="post"> {% csrf_token %} <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <input type="submit" class="btn btn-danger" value="Delete"> </form> </div> </div> </div> </div> Or maybe you could point me to some docs I could read. I'm new into programming and I'm learning based of off what my demo project needs. In this code, I used django templating for loop to loop through all the objects and posted em in a table. table has an option to delete which leads to a popup confirmation. Problem is I couldn't find any way to relay the data from the for loop part to the popup part where the post form is. -
auto-fill a form field with currently logged in user django
i have a form and when rendering should have some of the fields pre-filled and disabled with currently logged-in user, django. This is the rendered django form and under the username field should show only the current logged-in user and not all the registered users. views.py @login_required def teacherRecordForm(request): if request.user.is_authenticated: teacher_form = TeacherRecordForm if request.method == 'POST': teacher_form = TeacherRecordForm(request.POST, request.FILES) if teacher_form.is_valid(): teacher_form.save() messages.success(request, 'Details Saved Successfully') return redirect ('teacher-record-form') else: messages.success(request, 'check your information provided well') return render(request, 'schRecords/teacherRecordForm.html', {'teacher_form':teacher_form}) else: return render(request, 'schRecords/teacherRecordForm.html', {'teacher_form':teacher_form}) else: messages.success(request, 'kindly sign in first') return redirect('sign-in') -
In my python django projuct tried to host in godaddy cpanel but the pillow is not installing
In file included from src/libImaging/Imaging.h:688, from src/libImaging/XbmEncode.c:16: src/libImaging/ImagingUtils.h:35: warning: 'inline' is not at beginning of declaration cc1: warning: unrecognized command line option "-Wno-unused-result" cc1: warning: unrecognized command line option "-Wno-unused-result" cc1: warning: unrecognized command line option "-Wno-unused-result" gcc -Wno-unused-result -Wsign-compare -DNDEBUG -D_GNU_SOURCE -fPIC -fwrapv -O2 -pthread -Wno-unused-result -Wsign-compare -g -std=c99 -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -Werror=implicit-function-declaration -D_GNU_SOURCE -fPIC -fwrapv -D_GNU_SOURCE -fPIC -fwrapv -O2 -pthread -Wno-unused-result -Wsign-compare -g -std=c99 -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -Werror=implicit-function-declaration -fPIC -DHAVE_LIBJPEG -DHAVE_LIBZ -DHAVE_LIBTIFF -DHAVE_XCB -DPILLOW_VERSION=\"10.0.0\" -I/usr/include/freetype2 -I/usr/include -I/home/xhpnfadbs797/virtualenv/public_html/shopwithambro.com/3.9/include -I/opt/alt/python39/include/python3.9 -c src/libImaging/ZipDecode.c -o build/temp.linux-x86_64-cpython-39/src/libImaging/ZipDecode.o In file included from src/libImaging/Imaging.h:688, from src/libImaging/ZipDecode.c:18: src/libImaging/ImagingUtils.h:35: warning: 'inline' is not at beginning of declaration cc1: warning: unrecognized command line option "-Wno-unused-result" cc1: warning: unrecognized command line option "-Wno-unused-result" cc1: warning: unrecognized command line option "-Wno-unused-result" gcc -Wno-unused-result -Wsign-compare -DNDEBUG -D_GNU_SOURCE -fPIC -fwrapv -O2 -pthread -Wno-unused-result -Wsign-compare -g -std=c99 -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -Werror=implicit-function-declaration -D_GNU_SOURCE -fPIC -fwrapv -D_GNU_SOURCE -fPIC -fwrapv -O2 -pthread -Wno-unused-result -Wsign-compare -g -std=c99 -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -Werror=implicit-function-declaration -fPIC -DHAVE_LIBJPEG -DHAVE_LIBZ -DHAVE_LIBTIFF -DHAVE_XCB -DPILLOW_VERSION=\"10.0.0\" -I/usr/include/freetype2 -I/usr/include -I/home/xhpnfadbs797/virtualenv/public_html/shopwithambro.com/3.9/include -I/opt/alt/python39/include/python3.9 -c src/libImaging/ZipEncode.c -o build/temp.linux-x86_64-cpython-39/src/libImaging/ZipEncode.o In file included from src/libImaging/Imaging.h:688, from src/libImaging/ZipEncode.c:17: src/libImaging/ImagingUtils.h:35: warning: 'inline' is not at beginning of declaration cc1: warning: unrecognized command line option "-Wno-unused-result" cc1: warning: unrecognized command line option "-Wno-unused-result" cc1: warning: … -
Django/MSSQL: Issues counting objects depending on attribute
environment: Database: MSSQL Django 3.2.20 mssql-django 1.3 models class ChangeOrder(models.Model): # ...fields... class GroupChange(models.Model): order = models.ForeignKey( AssignmentChangeOrder, related_name='groupchanges' ) action = models.CharField(max_length=10, choices=['assignment', 'removal']) # ...other fields... class UserChange(models.Model): order = models.ForeignKey( AssignmentChangeOrder, related_name='userchanges' ) action = models.CharField(max_length=10, choices=['assignment', 'removal']) # ...other fields... objective For each ChangeOrder, I want to annotate/calculate: ant_assignment_count: Count of 'assignment' actions in both GroupChange and UserChange. ant_removal_count: Count of 'removal' actions in both GroupChange and UserChange. query ChangeOrder.objects.annotate( ant_assignment_count=Sum( Case( When(userchanges__action='assignment', then=1), When(groupchanges__action='assignment', then=1), default=0, output_field=IntegerField() ) ), ant_removal_count=Sum( Case( When(userchanges__action='removal', then=1), When(groupchanges__action='removal', then=1), default=0, output_field=IntegerField() ) ) ) objects co = ChangeOrder.objects.create() GroupChange.objects.create(order=co, action='removal', ..) GroupChange.objects.create(order=co, action='removal', ..) UserChange.objects.create(order=co, action='assignment', ..) If I run the query with those created objects I receive ant_assignment_count=2 and ant_removal_count=2. But it should be ant_assignment_count=1 and ant_removal_count=2. I've attempted various methods including annotations, subqueries, and Count with Case statements. However, I'm encountering issues and getting incorrect results. It seems to be a problem with the LEFT OUTER JOIN on GroupChange and UserChange. I'd appreciate any help! -
The cause of the error "List matching query does not exist."
I'm writing a Django auction program, and in the last levels of the program, when I wrote the code to select the winner of the auction and created the corresponding table with sqlite, I encountered this error. After this bug, no products will be displayed on the main page and product information cannot be seen. What is the cause of this error? I changed the names of the columns of the table, but it had no effect, and the rest of the code was working before creating this table. Exception Type: DoesNotExist at /auctions/1 Exception Value: List matching query does not exist. -
Django SearchFilter exists relationship without DISTINCT
Table search is implemented through rest_framework.filters SearchFilter with the addition of DISTINCT, which is not suitable for a large database, how to avoid this, what are the hacks for this class UserList(generics.ListAPIView): queryset = User.objects.order_by('-created') filter_backends=( SearchFilter, DjangoFilterBackend, ) search_fields = ( 'id', 'email', 'comments__id', ) thought about adding annotate(cnt=Count('comments',filter=Q(comments__id__icontains=search)).filter(cnt) to get_queryset, but then it's not clear when to do 'OR' -
Why is the django for traceback happening on my code wsv chapter 7?
File "/Users/russellanderson/Desktop/code/blog/.venv/lib/python3.11/site-packages/django/views/generic/edit.py", line 127, in get_success_url raise ImproperlyConfigured( ^ Exception Type: ImproperlyConfigured at /post/new/ Exception Value: No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model. -
Search with parent foreignkey, grandparent foreignkey in django-admin
I wanna be able to search a product with the category that isnt directly linked to it but the category is grandfather or great_great grandfather and so on above on the category tree of the category that is actually linked to the product itself. The only way i could implement was with the following which is ofcourse not scalable and proper way to do it: def get_queryset(self, request): queryset = super().get_queryset(request).select_related('brand', 'category', 'category__parent') category_name = request.GET.get('category__name', None) if category_name: # Filter the queryset to include products with the specified category or its ancestors queryset = queryset.filter( Q(category__name=category_name) | Q(category__parent__name=category_name) | Q(category__parent__parent__name=category_name) | # Add more levels as needed based on the depth of your category tree ) return queryset And here are the code as of now: Product``models.py class Product(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(blank=True, null=True) description = models.TextField() price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='product_images/') category = models.ForeignKey(Category, on_delete=models.SET_NULL,related_name='product_category', null=True, blank=True) brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, related_name='product_brand', null=True, blank=True) tags = GenericRelation(TaggedItem, related_query_name='product') ratings = GenericRelation(Rating, related_query_name='product') active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) state = models.CharField(max_length=2, choices=PublishStateOptions.choices, default=PublishStateOptions.DRAFT) publish_timestamp = models.DateTimeField( # means that the publish_timestamp field will not automatically be set to the current date … -
Save the user prompt that is sent from web terminal to django
I am running a terminal on browser using xterm.js. The program sends the input to django working in backend. The code in views.py is a modified version from MahmoudAlyy github page. The input in the pty_input method receives all the keys that user presses. It can be modified to get only the command but it would take a long time and be open to bugs. Is there another way to get only the user prompt by changing frontend or backend code? views.py: async_mode = "eventlet" sio = socketio.Server(async_mode=async_mode) fd = None child_pid = None def index(request): return render(request, "index.html") def set_winsize(fd, row, col, xpix=0, ypix=0): winsize = struct.pack("HHHH", row, col, xpix, ypix) fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize) def read_and_forward_pty_output(): global fd max_read_bytes = 1024 * 20 while True: sio.sleep(0.01) if fd: timeout_sec = 0 (data_ready, _, _) = select.select([fd], [], [], timeout_sec) if data_ready: output = os.read(fd, max_read_bytes).decode() sio.emit("pty_output", {"output": output}) else: print("process killed") return @sio.event def resize(sid, message): if fd: set_winsize(fd, message["rows"], message["cols"]) @sio.event def pty_input(sid, message): if fd: os.write(fd, message["input"].encode()) @sio.event def disconnect_request(sid): sio.disconnect(sid) @sio.event def connect(sid, environ): global fd global child_pid if child_pid: os.write(fd, "\n".encode()) return (child_pid, fd) = pty.fork() if child_pid == 0: subprocess.run("bash") else: print() sio.start_background_task(target=read_and_forward_pty_output) @sio.event … -
How can make api using fastapi for django project
I want my projects to be more faster and i decided to use fastapi for them.But can't import my django models and form to fastapi.can someone help me to make api using fastapi for django projects? any code? (for example blog project) -
Django + Gunicorn: how to run background worker thread?
I need to run a background thread in my Django application. During development i could run a thread that accesses my models launching it from the ready() function inside apps.py: def ready(self): from .tasks.mqtt_worker import MqttHandler mqtt_handler = MqttHandler() th1 = threading.Thread(target=mqtt_handler.task) th1.daemon = True th1.start() In Production using Gunicorn this approach seems to fail.. How can I start a background python thread that accesses some models in my application in production? I am running my app behind nginx like this: /software/cloud/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock iotapp.wsgi:application -
How to edit parents objects as a child?
I have two classes in my project. User has a parent object . class User(AbstractUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=255, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) parent = models.ForeignKey("self",on_delete=models.DO_NOTHING,related_name='child_sections', blank=True, null=True) class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='articles') caption = models.CharField(max_length=250) timestamp = models.DateTimeField(auto_now_add=True)``` Here a parent and the child itself can edit any objects class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ("id","author","caption","timestamp") def validate(self, attrs): attrs = super().validate(attrs) if attrs.get('parent').id == self.context['request'].user.pk return attrs elif attrs.get('id') == self.context['request'].user.pk return attrs raise ValidationError('Unauthorized Request') Here parent can edit its child's object and a user can edit its own object. What I want to do is simple: A child can also edit parents object. Can anyone help me?