Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to write a template for my views, I am just struggling to make it
{'totals': <QuerySet [ {'trans_mode': 'Cash', 'month': datetime.date(2023, 1, 1), 'tot': Decimal('99.25')}, {'trans_mode': 'Cash', 'month': datetime.date(2023, 2, 1), 'tot': Decimal('161.25')}, {'trans_mode': 'Cash', 'month': datetime.date(2023, 3, 1), 'tot': Decimal('40.5')}, {'trans_mode': 'ENBD', 'month': datetime.date(2023, 1, 1), 'tot': Decimal('2215.72000000000')}, {'trans_mode': 'ENBD', 'month': datetime.date(2023, 2, 1), 'tot': Decimal('1361.66000000000')}, {'trans_mode': 'ENBD', 'month': datetime.date(2023, 3, 1), 'tot': Decimal('-579.130000000000')}, {'trans_mode': 'NoL', 'month': datetime.date(2023, 1, 1), 'tot': Decimal('107')}, {'trans_mode': 'NoL', 'month': datetime.date(2023, 2, 1), 'tot': Decimal('56')}, {'trans_mode': 'NoL', 'month': datetime.date(2023, 3, 1), 'tot': Decimal('-69.5')}, {'trans_mode': 'Pay IT', 'month': datetime.date(2023, 1, 1), 'tot': Decimal('0')}, {'trans_mode': 'SIB', 'month': datetime.date(2023, 1, 1), 'tot': Decimal('208.390000000000')}, {'trans_mode': 'SIB', 'month': datetime.date(2023, 2, 1), 'tot': Decimal('-3.25')} ]>} above is the query set from Django views. I want to achieve the below, please suggest me a good way Trans Mode Jan 2023 Feb 2023 Mar 2023 Cash 99.25 161.25 40.5 ENBD 2215.72 1361.66 -579.13 NoL 107 56 -69.5 Pay IT SIB 208.39 -3.25 -
What would be the best way to handle situations that involves keeping records/history of fields based on the timerange_uuid?
Well, I think, I have run out of ideas and would like someone to help me explain using the example below. I have three tables (Timerange_uuid - should be an enum, and Person, and Organization), I want each time the Person changes an Organization (the Person can change organisations depending on the kind of work he/she is doing) the person's table should keep records of all Organizations that the person has served since the start date to end date - basing on the Timerange_uuid, and I can't figure out what would be the most appropriate solution to handle this situation. Timerange_uuid (enum) class Timerange_uuid(models.Model): start = models.DateTimeField(auto_now_add=True) stop = models.DateTimeField(auto_now=True) u = models.UUIDField(default=uuid.uuid4) class Meta: abstract = True Person class Person(models.Model): group_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) organization = ??? ## timerange_uuid[] -- organization_id Organization class Organization(models.Model): organization_id = models.UUIDField(primary_key=True ,default=uuid.uuid4, editable=False) -
Problem with static files while deploying django with docker-compose
I cannot serve the static files on my Django docker compose deployment. I want it for local deployment, using the built-in web server (runserver) My docker-compose: version: "3" services: app: build: context: ./app dockerfile: Dockerfile command: bash -c "./wait-for-mysql.sh mysqldb" depends_on: - mysqldb ports: - "8000:8000" volumes: - ./app:/app - ./app/static:/static environment: DJANGO_SETTINGS_MODULE: proteas2.settings.production DB_NAME: ${DB_NAME} DB_USER: ${DB_USER} DB_PASS: ${DB_PASS} DB_PORT: ${DB_PORT:-3306} DB_HOST: mysqldb env_file: - .env networks: - proteas mysqldb: image: mysql:latest command: ["--default-authentication-plugin=mysql_native_password"] ports: - "${DB_PORT:-3306}:3306" environment: MYSQL_DATABASE: ${DB_NAME} # MYSQL_USER: ${DB_USER} # MYSQL_PASSWORD: ${DB_PASS} MYSQL_ROOT_PASSWORD: ${DB_PASS} DJANGO_SUPERUSER_USERNAME: ${DJANGO_SUPERUSER_USERNAME} DJANGO_SUPERUSER_EMAIL: ${DJANGO_SUPERUSER_EMAIL} DJANGO_SUPERUSER_PASSWORD: ${DJANGO_SUPERUSER_PASSWORD} volumes: - ./db-data:/var/lib/mysql env_file: - .env networks: - proteas networks: proteas: I have: 'django.contrib.staticfiles' in my INSTALLED_APPS I tried to set: STATIC_URL = os.path.join(BASE_DIR, 'static/') STATIC_ROOT = 'static/' I ran collectstatic but did not make it work. -
How to run channel functions inside shared task function of celery in django?
I am working in a django proejct using celery , redis , rabbitmq , channels all together . I am using two queues Queue A and Queue B for my task assignment and i am using rabbitmq and redis for it. And i am using celery for background task . Now I want to run channels group_send function or in simpler terms i want to use channel functions inside the shared task function of celery so that i can use channels and send messages in real time from the shared task function. I have tried lots of ways but error still persists , every error mainly points towards the event loop that it is closed . Here is my views.py which runs the task function . def myView(request , *args , **kwargs) : try : myTask.delay({}) except Exception as e : print(e) return render(request , "app/htmlFile.html" , context = {} ) This is my tasks.py where i have created tasks and where i am using channel function ( group_send) to send message to the channels group . @shared_task(bind = True , queue = "A") def myTask(self , data): return None Now my various combinations where i used different methods to … -
filter select2 result based on logged in user
I have a select2 input in my django form and i want to filter the select2 options based on the logged in user for example I want user 1 to see options 1 and 3 but for user 2 options 1 snd 3 it's importatnt that my options themeselves are foreign keys from other tables here is my foreign key example: buyer = models.ForeignKey( Contact, on_delete=models.PROTECT, null=True, blank=True,related_name="buyer_contact_buy" ) and here is my ModelForm: class BuyForm(ModelForm): def __init__(self, *args, **kwargs): super(BuyForm, self).__init__(*args, **kwargs) for field_name in self.fields.keys(): self.fields[field_name].widget.attrs['class'] = 'form-control' self.fields['buyer'].widget.attrs['class'] = 'form-control ' + 'select2' class Meta: model = Buy exclude = ('id', 'creator_user',) and this is the js in my HTML: <script type="text/javascript"> $(document).ready(function () { // [ Single Select ] start $(".select2").select2(); }); </script> i had some search but i didnt get any result hope you guys can help me -
Django Channels: Mission Positional Arguments send and receive
Here My Consumer.py currently im developing a live chat system using django channels, but im facing below mentioned issue. please tell me how i can solve below mentioned issue. channels==4.0.0 ` import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.booking_id = None self.booking_group_name = None async def connect(self): self.booking_id = 2 self.booking_group_name = 'chat_%s' % self.booking_id # Join booking group await self.channel_layer.group_add( self.booking_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave booking group await self.channel_layer.group_discard( self.booking_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data=None, bytes_data=None): text_data_json = json.loads(text_data) sender = self.scope['user'] message = text_data_json['message'] # Save chat message to database await self.save_chat_message(sender, message) # Send message to booking group await self.channel_layer.group_send( self.booking_group_name, { 'type': 'chat_message', 'sender': sender.username, 'message': message } ) async def chat_message(self, event): sender = event['sender'] message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'sender': sender, 'message': message })) def save_chat_message(self, sender, message): from booking.models import Booking, CustomerSupportCollection, CustomerSupportChat booking = Booking.objects.get(id=self.booking_id) collection = CustomerSupportCollection.objects.get_or_create( booking=booking, ) chat_message = CustomerSupportChat.objects.create( booking=booking, collection=collection, user=sender, message=message ) return chat_message ` asgi.py """ ASGI config for cleany project. It exposes the ASGI callable as a module-level variable named … -
Remove unnecessary space between lines, flex-wrap tailwind-CSS
{% extends "base.html"%} {% block content %} <div class="place-content-center flex flex-wrap gap-3 mt-2 mb-3 xl:max-w-7xl"> {% for product in products %} <div class="h-fit rounded-md bg-white w-[45%] st:w-[30%] sm:w-[29%] md:w-[22%] lg:w-[18%] xl:w-[15%] shadow-lg"> <a href=""><img src="{{ product.image.url }}" alt="{{ product.name }} image"> <div class="ml-1 mr-1"> <h3 class="text-xs font-mono font-light">{{ product.name }}</h3> <h4> <span class="text-xs">KMF</span> <span class="font-semibold text-lg text-[#EF4444]">{{ product.price }}</span> </h4> </div> </a> <div class="flex place-content-center gap-5 m-2"><!--Shopping cart--> <div class="flex flex-col items-center"> <!--Shopping cart svg icon--> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-5 h-5 sm:w-6 sm:h-6"> <path d="M2.25 2.25a.75.75 0 000 1.5h1.386c.17 0 .318.114.362.278l2.558 9.592a3.752 3.752 0 00-2.806 3.63c0 .414.336.75.75.75h15.75a.75.75 0 000-1.5H5.378A2.25 2.25 0 017.5 15h11.218a.75.75 0 00.674-.421 60.358 60.358 0 002.96-7.228.75.75 0 00-.525-.965A60.864 60.864 0 005.68 4.509l-.232-.867A1.875 1.875 0 003.636 2.25H2.25zM3.75 20.25a1.5 1.5 0 113 0 1.5 1.5 0 01-3 0zM16.5 20.25a1.5 1.5 0 113 0 1.5 1.5 0 01-3 0z" /> </svg> </div> <!--Wish list--> <div class="flex flex-col items-center"> <!--Wish list svg icon--> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-5 h-5 sm:w-6 sm:h-6"> <path stroke-linecap="round" stroke-linejoin="round" d="M21 8.25c0-2.485-2.099-4.5-4.688-4.5-1.935 0-3.597 1.126-4.312 2.733-.715-1.607-2.377-2.733-4.313-2.733C5.1 3.75 3 5.765 3 8.25c0 7.22 9 12 9 12s9-4.78 9-12z" /> </svg> </div> </div> <div class="flex flex-col justify-center font-semibold text-xs gap-2 ml-1 … -
How can I display two testimonial cards in one slide using Django and Bootstrap?
I created a static testimonial section for my website, but I wanted to make it dynamic by adding a django model in my app for testimonials. I was able to fetch the data and show it on the page, but my design has two testimonial cards in one slide, and I'm struggling to implement this feature. Despite my attempts, I'm only able to display one testimonial card in the slide, which is ruining the design. Can anyone guide me on how to implement a solution for this issue? this is my model for testimonials class Testimonial(models.Model): name = models.CharField(max_length=100) content = FroalaField() image = models.ImageField(upload_to='testimonial/') def __str__(self): return self.name I added some data through Django admin and used the following HTML code to display the testimonials this is the staic html <!-- client section --> <section class="client_section py-5"> <div class="container"> <div class="d-flex justify-content-center"> <div class="container" style="text-align: center;"> <h2 class="sub-head">TESTIMONIAL</h2> <div class="small-heading"> <div class="line"></div> <span class="title">Words From Our Clients</span> <div class="line"></div> </div> </div> </div> <div id="carouselExample2Indicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExample2Indicators" data-slide-to="0" class="active"></li> </ol> <div class="carousel-inner"> <div class="carousel-item active"> <div class="client_container"> <div class="row"> <div class="col-md-6"> <div class="client_box"> <div class="detail_box"> <div class="img_box"> <img src="https://randomuser.me/api/portraits/women/28.jpg" /> </div> <h5> Valerie Hayes </h5> … -
Nginx not able to file gunicorn socket file http 502
5 connect() to unix:/var/run/mygunicorn.sock failed (2: No such file or directory) while connecting to upstream my gunicorn.service file [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=abc Group=www-data WorkingDirectory=/home/abc/mywork/xyz ExecStart=/home/abc/shoenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/var/run/mygunicorn.sock xyz.wsgi:application [Install] WantedBy=multi-user.target gunicorn.socket file [Unit] Description=gunicorn socket [Socket] ListenStream=/var/run/mygunicorn.sock [Install] WantedBy=sockets.target nginx server new sites-available server { listen 80;listen [::]:80; server_name <gunicorn server ip>; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/abc/shopcart; } location / { include proxy_params; proxy_pass http://unix:/var/run/mygunicorn.sock; } } I can curl it from gunicorn server curl --unix-socket /var/run/mygunicorn.sock localhost But when I try from nginx directory it cannot find socket file unix:/var/run/mygunicorn.sock failed (2: No such file or directory) while connecting to upstream socket file exists though srw-rw-rw- 1 root root 0 Apr 3 06:18 /var/run/mygunicorn.sock -
Django-graphene and tree structure output
Is it possible to make a tree structure output of the following type with the help of django-graphene? "mainMenu": [ { "pageSlug": "page-slug-01", "pageTitle": "page-title-01", "children": [ { "pageSlug": "sub_page-slug-01", "pageTitle": "sub_page-title-01", "children": [ ... ] }, ... { "pageSlug": "sub_page-slug-N", "pageTitle": "sub_page-title-N", "children": [ ... ] }, ] }, ... { "pageSlug": "page-slug-N", "pageTitle": "page-title-N", "children": [ ... ] }, ] I can't figure out how to describe the classes... -
Django is automatically clear expire sessions?
Django is automatically clear expire sessions? I just want to understand this. i search about this, but nothing -
Where is the parent html file in the Django app?
There is a Django app i am trying to modify. This is the code for it's base.html file: {% extends "base.html" %} {% load i18n %} {% block extra_head %} {{ block.super }} {% endblock %} {% block tabs %} <li><a href="{% url 'app_manager_base_url' %}">{% trans "Apps" %}</a></li> {{block.super}} <li><a href="{% url 'app_manager_base_url' %}">{% trans "Apps" %} asd</a></li> {% endblock %} {% block footer %} {% include 'cartoview/footer.html' %} {% endblock %} now here there are 3 tabs inside block.super. I want to change those tabs. But when i see the parent file then it says above extends base.html. The problem is that this file itself is named base.html and there is no other file of this name in this same directory. I want to locate the parent file so to change those tabs. Kindly help thanks. -
How to run midee doctr on specific area of image?
I am using below code to extract text from image with mindee/doctr package. from doctr.models import ocr_predictor from doctr.io import DocumentFile import json model = ocr_predictor( reco_arch='crnn_vgg16_bn', pretrained=True,export_as_straight_boxes=True) image = DocumentFile.from_images("docs/temp.jpg") result = model(image) result_json = result.export() json_object = json.dumps(result_json, indent=4) with open("temp.json", "w") as outfile: outfile.write(json_object) result.show(image) By using the mindee/doctr I got whole text form image in temp.json file. output after ocr I want to get text of specific area from the image. I don't have good approach to achieve that can someone help me to get out of it ? -
Django project deployment with Jenkins on AWS EC2 Instance
I have a Django project. Now I want to publish my project on AWS EC2 instance with Ubuntu AMI. To publish it, I want to use Jenkins as CI/CD pipeline. I really dont know what are the steps to deploy using Jenkins in AWS. I used normal project to publish it but suing Jenkins to deploy the project is problematic for me. But it is quite helpful than docker build as far I checked -
Django model update multiple instances with custom Manager function
I have a model class (for example A) inside the Django model framework. For this model I have created his Manager class with some functions. class T_Manager(BaseModelManager): def add_function(value): .... class T(BaseModel): objects = T_Manager() .... class A(BaseModel): t = GenericRelation('T', related_name='t') .... Now I have a list of A class objects and I would like to call add_function on all of them efficiently. I would like to use something like list_a.update(F('add_function', value)) or something like this. Is there a way to call this function inside the update function or what is recommended way to do this? -
Django models update multiple instance with foreign key objects in one transaction
In Django project I have three models: class First(BaseModel): ..... class A(BaseModel): b = models.OneToOneField('B', null=True, blank=True, related_name='B%(class)s', on_delete=models.PROTECT) first = models.ForeignKey('First', related_name='a_list', on_delete=deletion.PROTECT) class B(BaseModel): some_value = models.DecimalField(max_digits=20, decimal_places=6, null=True, blank=True) Inside one function, I would like to update the list of objects A with one transaction (so that I don't hit DB with multiple queries and updates). I tried something like this: first = First.objects.get(pk=id) list_a = first.a_list.filter(...).select_related('b') list_a.update(b__some_value=10) The problem is that I get the error: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/db/models/options.py", line 608, in get_field return self.fields_map[field_name] KeyError: 'b__some_value' During the handling of the above exception, another exception occurred: Traceback (most recent call last): File "", line 2423, in ... resp = mview.post(self.get_url(), data=data, format='json') .... File "/usr/local/lib/python3.7/site-packages/django/db/models/options.py", line 610, in get_field raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name)) django.core.exceptions.FieldDoesNotExist: A has no field named 'b__some_value' Does anyone know why I get this error or how to achieve the same results? -
How do I run ASGI alongside WSGI on Heroku with NGINX, Django, uWSGI, and Daphne?
Something is wrong with nginx start up and connecting to websockets but I'm having trouble figuring out how to solve it. Looking at the heroku logs, the Daphne process end up getting an error "CRITICAL Listen failure: Couldn't listen on unix:/tmp/nginx.socket:48560: [Errno -2] Name or service not known." And the web process just keeps printing "buildpack=nginx at=app-initialization" every second. Here is my code: Procfile: release: python manage.py migrate web: bin/start-nginx-debug uwsgi uwsgi.ini daphne: daphne my_project.asgi:application --port $PORT --bind unix:/tmp/nginx.socket -v2 worker: celery -A my_project worker -l info nginx.conf.erb: daemon off; # Heroku dynos have at least 4 cores. worker_processes <%= ENV['NGINX_WORKERS'] || 4 %>; events { use epoll; accept_mutex on; worker_connections <%= ENV['NGINX_WORKER_CONNECTIONS'] || 1024 %>; } http { gzip on; gzip_comp_level 2; gzip_min_length 512; gzip_proxied any; # Heroku router sends Via header server_tokens off; log_format l2met 'measure#nginx.service=$request_time request_id=$http_x_request_id'; access_log <%= ENV['NGINX_ACCESS_LOG_PATH'] || 'logs/nginx/access.log' %> l2met; error_log <%= ENV['NGINX_ERROR_LOG_PATH'] || 'logs/nginx/error.log' %>; include mime.types; default_type application/octet-stream; sendfile on; # Must read the body in 5 seconds. client_body_timeout 5; # upstream for uWSGI upstream uwsgi_app { server unix:///tmp/nginx.socket; #unix:/app/my_project/uwsgi_app.sock; # } # upstream for Daphne upstream daphne { server unix:///tmp/nginx.socket; #unix:/app/my_project/daphne.sock; } server { listen <%= ENV["PORT"] %>; server_name _; keepalive_timeout … -
chatbot using python, django, openai, speech recognition
I have implemented virtual assistance using speech recognition,openai,pyttsx3.it's working on console, I want to create a web app using django. console result -
Upload KML data from Google Earth to django Models
I have a model class Area(models.Model): name = models.CharField(max_length = 255) point = postgis.PointField(null = True, blank = True) area = postgis.MultiPolygonField(null = True, blank = True) I have a kml file which consist of different areas and I want to upload it into this model so later I can add the foreign key of the area in other table How to do that? -
Django - solving a possible n + 1 problem
One of my views is hitting the db a lot with a particular query. Scout-apm identifies it as a possible n+1 query. I'm not sure that is the problem, but it is a problem nonetheless. My original code was: models.py class Grade(models.Model): score = models.CharField(max_length=4, blank=True) testing = models.ForeignKey(Testing, on_delete=models.CASCADE) student = models.ForeignKey(Student, on_delete=models.CASCADE) classroom = models.ForeignKey(Purpose, on_delete=models.CASCADE) time_created = models.DateField( auto_now=False, auto_now_add=False, default=timezone.now) Class Testing(models.Model): name = models.CharField(max_length=20, blank=True) omit = models.BooleanField(default=False) Class Classroom(models.Model): name = models.CharField(max_length=20, blank=True) views.py def allgrades(request, student_id): classrooms = Classroom.objects.all() for c in classrooms: q = Grade.objects.filter( student=student_id, classroom=c.id, testing__omit="False").order_by('-time_created') if q.exists(): if len(q) < 3: qn = q.first() else: .... The offending queries come from the if q.exists(): and qn = q.first(). I don't know if this falls in the category of n + 1, but the number of queries decreases from around 1300 to around 400 if I get rid of the if q.exists(): and qn = q.first() I need the functionality of these statements. Since I'm doing something with q, I need to check that it exists. And as the code shows, I may want to only include the newest object. Is there a less expensive way to deal with this? -
How do I create multiple lines in my string for my Blog site?
from django.conf import settings from django.db import models # Create your models here. class BlogPost(models.Model): title = models.CharField(max_length=200) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return f"Title: {self.title}\nBlog: {self.text}" I introduced the f-string format and attempted to utilize the "\n" method but the output is still on same line when I run my server. -
I am getting "Incorrect type. Expected pk value, received str." using fk in drf
This is my model. class Counter(models.Model): userid = models.ForeignKey(Identification,related_name="userName",verbose_name=_("User ID"), on_delete=models.CASCADE, null=True) counter = models.IntegerField(_("Counter"), blank=True, null=True) date_and_time = models.DateTimeField(_("Date and Time"), default=timezone.now) def __str__(self): return str(self.counter) This is my serializer. class Message_Counter_Serializer(serializers.ModelSerializer): userid = serializers.SlugRelatedField( slug_field='userName', queryset=Identification.objects.all() ) class Meta: model = Counter fields = '__all__' This is my View class Counter_Viewsets(errorhandler, viewsets.ModelViewSet): permission_classes = [permissions.IsAuthenticated, TokenHasResourceScope] serializer_class = Message_Counter_Serializer def get_queryset(self): return Counter.objects.all().filter(userid__user_name=self.request.user) ** This is my Post Request:** { "counter": "2", "userid": "yasmin" } -
Can not get validation during json deserialization with django rest framework
I am working on a django application that fetch data from an API. The json I get looks like this : { "id":"game_id", "players":{ "white":{ "user":{ "name":"player1", "id":"player1" }, "rating":11, "stars":58 }, "black":{ "user":{ "name":"player2", "id":"player2" }, "rating":10, "stars":52 } } } I am trying to deserialize it to insert data in a "game" database : class User(models.Model): id = models.CharField(primary_key=True, max_length=100) name = models.CharField(max_length=100) class Game(models.Model): id = models.CharField(primary_key=True, max_length=15) white = models.ForeignKey(User, related_name="white_id", on_delete=models.CASCADE) white_rating = models.IntegerField() white_stars = models.IntegerField() with the following serializers : class PlayersSerializer(serializers.BaseSerializer): def to_internal_value(self, data): white = data.get("players").get("white") white_id = white.get("user").get("id") white_rating = white.get("rating") white_stars = white.get("stars") return {"white": white_id, "white_rating": white_rating, "white_stars": white_stars} class GameSerializer(serializers.ModelSerializer): white = PlayersSerializer() white_rating = PlayersSerializer() white_stars = PlayersSerializer() class Meta: model = Game fields = ["id", "white", "white_rating", "white_stars"] When in the view file I check GameSerialization.is_valid(data), I get the following error: {'white': [ErrorDetail(string='This field is required.', code='required')], 'white_rating': [ErrorDetail(string='This field is required.', code='required')], 'white_stars': [ErrorDetail(string='This field is required.', code='required')]} -
Django ModelSerializer is receiving an empty set for the context
When I am passing the context via DRF the serializer is getting an empty set it seems. When I look at what self.context prints, it is "{}". End goal with all of this is to be able to 1. filter nested serializers based on context data and 2. pass context data in nested serializers. Here is my view: @api_view(['POST']) @permission_classes([IsAdminUser]) def unitUpdate(request, pk): request.data._mutable = True request.data['tenant'] = request.user.tenant unit = Unit.objects.filter(unit_id = pk,tenant=request.user.tenant) context = {'request': request} serializer = UnitSerializerCreate(instance=unit, data=request.data,context=context) if serializer.is_valid(): serializer.save() return Response(serializer.data) Here is my Serializer class UnitSerializer(serializers.ModelSerializer): rooms = serializers.SerializerMethodField('get_rooms') #filter(tenant=self.context['request'].user.tentant) def get_rooms(self, obj): print(self.context) room_instances = Room.objects.filter(tenant=self.context['request'].user.tenant) return RoomSerializer(room_instances, many=True) return None class Meta: model = Unit fields = ['unit_id','unit_name','description','rooms','tenant'] Have tried many different ways of passing context and even passing in statically defined dictionaries but they always come out as empty sets -
django utf-8 urls works on local but not working on production
i have a django project that on local the urls are ok and opens normally but on live server the utf-8 urls get 404 error here is my urls.py from django.conf import settings from django.conf.urls.static import static from django.urls import re_path from .views import law_list, law_detail, post_detail, category_detail app_name = 'book' urlpatterns = [ re_path(r'^$', law_list, name='law_list'), re_path(r'^(?P<law_id>\d+)/$', law_detail, name='law_detail'), re_path(r'^(?P<law_id>\d+)/(?P<law_slug>[-\w]*)/$', law_detail, name='law_detail_slug'), re_path(r'^categories/(?P<category_id>\d+)/$', category_detail, name='category_detail'), re_path(r'^categories/(?P<category_id>\d+)/(?P<category_slug>[-\w]*)/$', category_detail, name='category_detail_slug'), re_path(r'^posts/(?P<post_id>\d+)/$', post_detail, name='post_detail'), re_path(r'^posts/(?P<post_id>\d+)/(?P<post_slug>[-\w]*)/$', post_detail, name='post_detail_slug'), ] # Add the following lines to serve static files if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) thanks i tried to add allow_unicode = true to settings.py but it didnt work!