Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use of queryset inside the primarykeyrelated field in django serializers
I am quite confused why we have to write queryset = Example.objects.all() inside the modelserializer class when I creating an object using a foreign key in the post http call. For eg: class ExampleSerializer(serializers.ModelSerializer): abc = serializers.PrimaryKeyRelatedField(queryset=Abc.objects.all()) class Meta: model = Class fields = ['id','abc'] def create(self, validated_data): ...........// class Example(models.Model): abc = models.Foreignkey(Abc) If it was a get call I can use read_only= True inside the abc pk field, but since it is to be written I am passing a single id from the frontend, but why I need to populate all objects inside the serializer field. The docs says something like this : The queryset used for model instance lookups when validating the field input but cant gather what it is saying. -
Python/Django subscripe permanently to a MQTT Mosquito topic and get data
In my django project i would to subscribe to an MQTT topic forever and trigger actions when topic change. In my __init__.py application file i try: client1 = mqtt.Client(hex(uuid.getnode())) data_dict = init_client('IOT/Data/#') for k, v in data_dict.items(): ...do some stuff with data the init_client function connect to my MQTT server and start loop ( i use paho.mqtt.client): def init_client(t_topic='IOT/Data/#'): # Instantiate and check connection about MQTT instance client1.on_connect = on_connect # attach function to callback client1.on_message = on_message # attach function to callback if t_topic == 'IOT/Data/#': client1.message_callback_add(t_topic, on_message_data) else: client1.message_callback_add(t_topic, on_message_reg) client1.on_publish = on_publish # attach function to callback # client1.on_subscribe =on_subscribe # attach function to callback try: client1.tls_set(mqtt_ca_crt, mqtt_cli_crt, mqtt_cli_key) client1.tls_insecure_set(True) except ValueError: logging.info("SSL/TLS Already configured") time.sleep(1) try: if not client1.is_connected(): client1.connect(mqtt_server, mqtt_port) # connect to broker client1.connected_flag = False except Exception: logging.error("Cannot connect MQTT Client1") client1.loop_forever() ...and some other stuff the problem is when loop_forever() start all django application got in hold, whaiting forever. So my question is: How can i subscibe to a topic with paho.mqtt (asynchronously) when my django allpication start and get notified every time the topic change in real time? There are others more smart way with django to do this? So many … -
django orm take to much time in mysql and server
we have a script in django and this script add csv rows to the database. when we do it in local and with sqlite script do the job so fast but when we do it in server and with mysql it take too much time. I debug the script and I found out after some row when we reach line of getting first object it takes to much time for response code: filtered=Stock_Csv.objects.filter(ticker=name) filtered_by_date=filtered.filter(date=date_object) current_obj=filtered_by_date.first() when reach this line:current_obj=filtered_by_date.first() it takes to much time for response but it's just happened in mysql and in local we don't have this problem. -
How to use different lookup field in each request of one class
Want access the different request by using the different lookup fields. I have use the simplerouter in router and ModelViewSet in views of the django rest framework. Example of the expected use case: url to perform update - /user/{id}/ url to perform delete- /user/{creation_date}/ Please help to solve the problem. Thanks. -
Django staff user permisssions
Hi I have created a staff user in Django to limit the permissions. but when i login from the staff user I am able to do all the stuff which superuser can do. how to restrict these permissions for a staff user? Please help me with this... -
Django chain filters of child objects
I have Parent and Child models and try to filter in a chain child objects by condition objects = Parent.objects.all() if val1: objects = objects.filter(children__arg1=val1) if val2: objects = objects.filter(children__arg2=val2) If I make a chain of children filtering, Django makes several JOIN with individual WHERE Smth like this: JOIN "children" c1 ON c1."parent_id" = "parent"."id" JOIN "children" c2 ON c2."parent_id" = "parent"."id" WHERE c1."arg1" = val1 AND c2."arg2" = val2 I could filter Child at first: filtered_children = Child.objects.all() if val1: filtered_children = filtered_children.filter(arg1=val1) if val2: filtered_children = filtered_children.filter(arg2=val2) And then objects = Parent.objects.filter(children__in=filtered_children) But then I lose objects withno children. So I have to do smth like this: objects = Parent.objects.all() if val1 or val2: #'filter was applied' detection objects = objects.filter(children__in=filtered_children) Looks bad. Is there any better approach to filter child objects by condition? -
How do confirm_publish and acks_late compare in Celery?
I've noticed the following in the docs: Ideally task functions should be idempotent: meaning the function won’t cause unintended effects even if called multiple times with the same arguments. Since the worker cannot detect if your tasks are idempotent, the default behavior is to acknowledge the message in advance, just before it’s executed, so that a task invocation that already started is never executed again. If your task is idempotent you can set the acks_late option to have the worker acknowledge the message after the task returns instead. See also the FAQ entry Should I use retry or acks_late?. If set to True messages for this task will be acknowledged after the task has been executed, not just before (the default behavior). Note: This means the task may be executed multiple times should the worker crash in the middle of execution. Make sure your tasks are idempotent. Then there is the BROKER_TRANSPORT_OPTIONS = {'confirm_publish': True} option found here. I could not find official documentation for that. I want to be certain that tasks which are submitted to celery (1) arrive at celery and (2) eventually get executed. Here is how I think it works: Celery stores the information which tasks … -
Common models in Django Rest Framework
I found this very useful article how to use common models in the DRF. Common Models in Django and the DRF So I wanted to have a create_by, created_when, updated_by and updated_when attribute for all by objects in the database. I used the viewsets.ModelViewSet together with mixins.ListModelMixin and mixins.CreateModelMixin before and it worked. I just replaced the viewsets.ModelViewSet with my new CommonViewSet class. This is my code: views.py class CommonViewSet(viewsets.ModelViewSet): """Ensure the models are updated with the requesting user.""" def perform_create(self, serializer): """Ensure we have the authorized user for ownership.""" serializer.save(created_by=self.request.user, updated_by=self.request.user) def perform_update(self, serializer): """Ensure we have the authorized user for ownership.""" serializer.save(updated_by=self.request.user) class TagViewSet(CommonViewSet, mixins.ListModelMixin, mixins.CreateModelMixin): """Manage tags in the database""" authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) queryset = Tag.objects.all() serializer_class = serializers.TagSerializer serializers.py class CommonSerializer(serializers.ModelSerializer): """Ensure the fields are included in the models.""" common_fields = ['created_by', 'created_at', 'updated_by', 'updated_at'] class TagSerializer(CommonSerializer): """Serializer for tag objects""" class Meta: model = Tag fields = (['id', 'name'] + CommonSerializer.common_fields) read_only_fields = ('id',) models.py class CommonModel(models.Model): """Common fields that are shared among all models.""" created_by = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.PROTECT, editable=False, related_name="+") updated_by = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.PROTECT, editable=False, related_name="+") created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_at = models.DateTimeField(auto_now=True, editable=False) class Tag(CommonModel): """Tag to be used for device type""" … -
Display message in real time django using JS
I have a program that converts word documents to pdfs using django. The number of documents varies. I want to know how to send a text to the homepage after each document has been converted. The Id is stored in a variable in my views.py For example : "S 123 done" if the id is S 123 I'm very new to JS. It would be great if someone can help -
Uvicorn shutsdown everytime a websocket connection is active an the autoreload is triggered by watchman
I have added websockets to my Django application through Django Channels, and I am using uvicorn as asgi. I have configured uvicorn to hotreload whenever there's a file change, the issue is, whenever there's an active websocket connection active and it tries to reload itself I get this error. Waiting for background tasks to complete. (CTRL+C to force quit) I have verified that it's happening because of the active websocket connection otherwise it doesn't happen. Here are the params I am passing to uvicorn. uvicorn --reload --host 0.0.0.0 --port 8010 --workers 3 app.asgi:application --timeout-keep-alive 5000 -
Django-Store to DB with Crontab by means of a for loop and API calls
My problem is that my crontab script does not enter into the first loop and therefore does not store the values that I am trying to store. In my settings file I have the following: INSTALLED_APPS = [ 'django_crontab', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'my_app',] and a little further down: CRONJOBS = [ ('*/30 * * * * ', 'ms_app.cron.node_count_and_store'),] In my cron file I make use of an API that is working correctly, I will not add this here but it basically collects 'nodes' and stores them in a list in this format: node_list = [[owner, location, serial_number, state]] This node list (about 6000 in length) is used in the following code: node = models.Node.objects node_list_len = len(node_list) for k in range(node_list_len): print(k) if node.filter(node_serial=node_list[k][2]).exists() == True: node_ref = node.filter(node_serial=node_list[k][2]) node_ref.connection_state = node_list[k][3] node.save() print("Found the node: %s"%node_list[k][2]) elif node.filter(node_serial=node_list[k][2]).exists() == False: node.create( owener_id=node_list[k][0], location_id=node_list[k][1], node_serial=node_list[k][2], connection_state=node_list[k][3] ) node.save() print("Created the node: %s"%node_list[k][2]) else: print("Do nothing") return The above snippet is in the function def node_count_and_store() What I don't understand is that when I use the Django shell and import my models and apply the exact same code I can loop through my list and store the node … -
IndentationError: expected an indented block error for my python first web app
views.py", line 6 return HttpResponse('Hello Buddy How are you') ^ IndentationError: expected an indented block -
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'app.User' that has not been installed
this question has been asked a lot of times but I am asking it because I still cannot find any workable solution. I am trying to create a custom user model using AbstractBaseUser inside the myapp app and I have written the app name inside INSTALLED_APPS and the command AUTH_USER_MODEL = 'myapp.User' inside settings.py. The command python manage.py makemigrations --dry-run works perfectly without any errors when my custom user model is stored within the default model file location at backend/myapp/models.py but I want to rename and move this file to the directory backend/myapp/models/user.py and have it stored along with other models. Whenever I try and move or rename the backend/myapp/models.py file which has my custom user model, Django returns the django.core.exceptions.ImproperlyConfigured error. Need help. Thanks backend/myapp/models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser class User(AbstractBaseUser): id = models.CharField(max_length=15, null=False, blank=False, primary_key=True, unique=True) USERNAME_FIELD = "id" Current folder structure: [backend]/ ├── [core]/ │ ├── __pycache__/ │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ ├── wsgi.py ├── [env]/ ├── [myapp]/ │ ├── __pycache__/ │ ├── migrations/ │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── models.py ├── manage.py django.core.exceptions.ImproperlyConfigured: C:\Users\amand\Documents\_My Files\project\app\backend>python manage.py makemigrations --dry-run … -
Django SUM 2 Column with Different Condition
In Django how to sum 2 column with different condition, how i try to sum column amount with condition trx=2 and amount with condition trx=3 reportusage = (Invoices.objects .annotate(month=ExtractMonth('datetime')) .values('month') .annotate(total=Sum('amount').filter(trx=2) + Sum('amount').filter(trx=3), product=F('tenant')) .order_by()) -
Django, warning as VIEW return queryset unordered
The Django view templates takes parameters from url,filter database and output as list. Even though I have added the ordering , I get result unordered class PostListView(ListView): model = Post template_name = ** ordering = ['-created_at'] paginate_by = 5 def get_queryset(self, *args, **kwargs): **** return posts -
Manytomanyfields issue : Fetch the columns where the manytomanyfield is applied
(Sorry for the inappropriate title. I am very bad at english. So I couldn't find out what should be the title) I have 2 tables Devices and groups class Devices(models.Model): id = models.AutoField(primary_key=True) device_name =\ models.CharField(max_length=100, null=False) class Groups(models.Model): group_id = models.AutoField(primary_key=True) devices = models.ManyToManyField(Devices, blank=True) I have more than 100000 devices and 100 groups. The devices can have multiple groups. I want to fetch the group_ids each device is having. I tried to loop through all the devices and fetch the group column. But it is taking too much time. Is there any pythonic way to solve this? -
Django inline formset not saving default values
I have a child inlineformset that saves if it has been changed by the user, but does not save the default value if left unchanged. SeVsEff is the child, and patient is the parent models.py class Patient(TimeStampedModel): patient_id = models.UUIDField( primary_key=True, unique=True, default=uuid.uuid4, editable=False ) name = models.CharField("Patient Name", max_length=255) user = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL ) class SeVsEff(TimeStampedModel): value = models.IntegerField(default=20) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) forms.py class PatientForm(ModelForm): class Meta: model = Patient fields = ["name"] SevseffFormSet = inlineformset_factory( Patient, SeVsEff, fields=("value",), widgets={'value': RangeInput()}, extra=0, min_num=1, validate_min=True, labels=None, ) views.py def post(self, *args, **kwargs): form = PatientForm(data=self.request.POST) sevseff_formset = SevseffFormSet(data=self.request.POST) if form.is_valid(): patient_instance = form.save() patient_instance.user = self.request.user patient_instance.save() if sevseff_formset.is_valid(): sevseff_name = sevseff_formset.save(commit=False) for sevseff in sevseff_name: sevseff.patient = patient_instance sevseff.save() So I think the issues is that the sevseff_formset is not registered as valid unless it is changed, but if I add something like: if not sevseff_formset.has_changed(): sevseff_name = sevseff_formset.save(commit=False) for sevseff in sevseff_name: sevseff.patient = patient_instance sevseff.save() This doesn't work as sevseff_name is empty. -
How to upload multiple file in django create view where the total number of files can be uploaded is not fixed
i had created a form to fill up by the users where the user can upload multiple files which is not fixed(like they can upload 1 or 2 and so on).So how to achieve this in django create view -
How to extract top 2 by group in django queryset
Django queryset related question. Feedback class model contains the student registration date, etc... Assignment class model contains student personal information, and Level class model contains the class to which the student belongs. I want to print out the two students with the earliest registration date for each class. Using the max function, the first student registered by class can be printed, Feedback.objects.filter(assignment__is_deleted=0)\ .values('assignment__level')\ .annotate(first=Max('ICF_date')) but how to print the second registered student by class? I would like the result to be printed in one line. -
React While calling API : Access to XMLHttpRequest has been blocked by CORS policy
I am using Django rest api in React but I am getting this as Error: Access to XMLHttpRequest at 'http://127.0.0.1:8000/list/single/6' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. <------- Can anyone help me in brief Please? I need to complete my project for this solution I am searching for a week. If you left your Telegram id then it would be great to solve for me you can delete it later for privacy. -
How can i query multiple objects, filtering with multiple id's
class Timeline(models.Model): license = models.ForeignKey(License, on_delete=models.CASCADE) last_renewed = models.DateField() due_date = models.DateField() def home(request): title = "Licences" agencies = Agency.objects.all() agent =Agency.objects.get(pk=1) licenses = License.objects.all() for license in licenses: print(license.id) timeline = Timeline.objects.select_related().filter(license_id = license.id).order_by('-id')[:1] I want to display at least one timeline related to each of the licenses that i am querying -
How can I pass variable in dynamic URL in Django Template
So I have a blog site and I want that when someone clicks on the delete button so the blog should delete. But the slug in the URL is a Variable how I can pass it? URL path: code:"path('deletePost/slug:slug', views.deletePost, name='deletePost')," I have passed the variable "Del_slug" to this view so how can I use it in the URL. code:"Delete" -
I have django application running on apache+docker on port 8000:80,need to run another application with another port but not working
I have Django application running with apache+docker with 8000:80 port in ubuntu server. Now I have another Django application. I want to run that application with apache+docker with different port 8006 or any other port. I think we can't bind two applications for the same port 80.Correct me if I am wrong and suggestions are most welcome. I am able build docker container and service is up, but I'm not accessible on browser and requests. So, is there any way that I can do it and able to access in browser please suggest Here is my docker-compose.yml version: '3.1' services: test-app: image: test-app build: context: ./app/ ports: - "8006:8006" # networks: # - GST container_name: test-app environment: - TZ=Asia/Kolkata restart: on-failure volumes: - /storage/req_resp_files:/var/www/html/GSTDP_Develop/req_resp_files - /storage/gst_logs:/var/www/html/GSTDP_Develop/logs Here is my Dockerfile FROM httpd:latest RUN apt-get update RUN apt-get install -y apt-utils vim curl apache2 apache2-utils RUN apt-get -y install python3 libapache2-mod-wsgi-py3 RUN ln /usr/bin/python3 /usr/bin/python RUN apt-get -y install python3-pip RUN ln /usr/bin/pip3 /usr/bin/pip RUN pip install --upgrade pip RUN pip install django ptvsd ADD ./demo_site.conf /etc/apache2/sites-available/000-default.conf #ADD ./httpd-ssl.conf /usr/local/apache2/conf/extra/httpd-ssl.conf #ADD ./server.key /usr/local/apache2/conf/server.key #ADD ./server.crt /usr/local/apache2/conf/server.crt #ADD ./gd_bundle-g2-g1.crt /usr/local/apache2/conf/gd_bundle-g2-g1.crt ADD ./GSTDP_Develop /var/www/html/GSTDP_Develop RUN chown -R www-data. /var/www/html/GSTDP_Develop RUN chown -R www-data. … -
In which part of Django application a user is made authenticated?
I am trying to restrict multiple logins by a user with the use of sessions Below is my code my model class LoggedInUser(models.Model): user = models.OneToOneField(CustomUser, related_name='logged_in_user', on_delete =models.CASCADE) session_key = models.CharField(max_length=40, null=True, blank=True) def __str__(self): return self.user.username my middlware ef MySessionMiddleware(get_response): def my_function(request): if request.user.is_authenticated: try: user = LoggedInUser.objects.filter(user=request.user).first() except: user = LoggedInUser.objects.create(user=request.user) if user.session_key: #check whether old key is same as current print('here inside user.session_key') if user.session_key != request.session.session_key: return JsonResponse("you already have a active session kindly logout from that", status=400, safe=False) user.session_key = request.session.session_key user.save() response = get_response(request) return response return my_function my middleware setting 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', 'pwned_passwords_django.middleware.PwnedPasswordsMiddleware', 'oneFA.middlewares.password_validator_middleware', 'oneFA.middlewares.MySessionMiddleware', ] my logic I created a model which stores a user with OnetoOne field with CustomUSer which is my authenticated model, and a session key then everytime i made a call i am trying to check the current session key with previous one and if it is not same then a user is trying to login again so i am returning error my error request.user.is_authenticated is always coming false which means that user is not authenticated now , i even tried placing my middleware ahead of authentication middleware and … -
how to make a url variable available to all the template
I have a specific requirement - say I hit the url as below - http://127.0.0.1:8000/brand_product_list/1 in the above url the last 1 is a brand-id and I need this brand-id to be available to all the templates for eg. if I call my brand_product_list looks like below in views.py - # Product List as per Brand1 def brand_product_list(request,brand_id): brandid = brand_id brand_b=Brand.objects.get(id=brand_id) cats_b=Product.objects.filter(brand=brand_b).distinct().values('category__title','category_id') data_b=Product.objects.filter(brand=brand_b).order_by('-id') colors_b=ProductAttribute.objects.filter(brand=brand_b).distinct().values('color__title','color__id','color__color_code') sizes_b=ProductAttribute.objects.filter(brand=brand_b).distinct().values('size__title','size__id') flavors_b=ProductAttribute.objects.filter(brand=brand_b).distinct().values('flavor__title','flavor__id') return render(request,'brand_product_list.html', { 'data_b':data_b, 'brandid':brandid, 'cats_b':cats_b, 'brand_b':brand_b, 'sizes_b':sizes_b, 'colors_b':colors_b, 'flavors_b':flavors_b, }) in the above code I need brandid to be available in cart.html which is called from clicking cart button in base.html which is extended in brand_product_list.html point is since base.html is extended in brand_product_list.html, the brandid is available to base.html (means child variable available in parent) and I can filter stuff based on brand but somehow when I click on cart button in base.html, the same brandid is not taken to cart.html even though base.html is extended in cart.html (means parent variable not available in child). I tried include as below {% include "./brand_product_list.html" %} but since in brand_product_list.html, there is some filter.html, it throws error that argument is not available -- NoReverseMatch at /cart Reverse for 'filter_data_b' with arguments '('brandid',)' not …