Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
what is the best way to use has_usable_password in Django 3 templates?
I would like to add condition in my template to see if user password is set or not. Something like this doesn't work for me because I cannot put it in my html: >>> a = User.objects.create_user('user1', 'user1@example.com') >>> b = User.objects.create_user('user2', 'user2@example.com', password='secret') >>> a.has_usable_password() False >>> b.has_usable_password() True I tried to put has_usable_password in html as template tag but it doesn't work: {% if user.has_usable_password == True %} password ok {% else %} password not set {% endif %} Something like this is also not working {% if user.has_usable_password %} passord ok {% else %} password not set {% endif %} But if I go to admin panel I see password not set -
Use filterset class in a nested route in Django REST Framework
We have a REST API created with Django and Django REST Framework. With the package django-filter I've created a FilterSet class which I want to use in a nested route. For illustration, we have model classes User, Post, Tag. A Post has one author (User) and can have many (or none) Tags. The following endpoints are present: /users/[id]/ /posts/[id]/ /users/[id]/posts/ The FilterSet class looks like this: class PostFilterSet(filters.FilterSet): tags = filters.ModelChoiceFilter(queryset=Tag.objects.all()) class Meta: model = Post fields = ("tags",) We use it in the viewset for Posts: class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all() filter_backends = [filters.DjangoFilterBackend] filterset_class = PostFilterSet Now this is working well and the list of posts can be filtered by tag, like this: /posts/?tags=some_tag In the UserViewSet we have a nested route created with the decorator action: class UserViewSet(viewsets.ReadOnlyModelViewSet): @action(methods=["get"], detail=True) def posts(self, request, pk): # logic to fetch posts for the given user return Response(serializer.data) We want to filter the list of posts for a given user (author) tagged by some tag: /users/[id]/posts/?tags=some_tag I want to use the PostFilterSet class in the nested route above. Is this possible? If yes, how should it be done? -
Unable to understand why the error is occurring
I have been trying to concatenate two strings and assign them to a cell in an excel sheet. I am however unable to understand why the below-shown error is occurring as I cannot find any error in the functioning of the rest of the code the error shown is: Traceback (most recent call last): File "C:\Users\AdvaitSNambiar\Desktop\Myfolder\SUTT task\Final\task1test-2-final.py", line 63, in <module> ws['D' + str(i) ].value = ws['D' + str(i)].value + '+ EEE' TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' if (h2 == 'A3'): ws['D' + str(i) ].value = ws['D' + str(i)].value + '+ EEE' this was the concatenation I tried to perform my code is given below import openpyxl from openpyxl import load_workbook wb = load_workbook('names.xlsx') ws = wb.active i = 0 while(i<24): i = 2 while(i<24): idnum = ws['A' + str(i)] idnum1 = idnum.value idnum2 = idnum1[4:8] if (idnum2 == 'AAPS'): ws['D' + str(i)] = 'ECE' if (idnum2 == 'ABPS'): ws['D' + str(i) ] = 'Manu' if (idnum2 == 'A1PS'): ws['D' + str(i)] = 'chemical' if (idnum2 == 'A2PS'): ws['D' + str(i) ] = 'civil' if (idnum2 == 'A3PS'): ws['D' + str(i) ] = 'EEE' if (idnum2 == 'A4PS'): ws['D' + str(i)] = 'Mech' if (idnum2 == … -
Pass html in to another html
Hello dear community, First of all, I've been trying to solve the problem for x hours, but so far I've failed transiently. You are Tmm a last opening. I am currently involved in a project where we are developing a quiz game. I am responsible for the backend. We want users to be able to add questions to the game as well, but when a user adds a question, it should be saved to the database before the question. As soon as the user adds a question, the admin gets an email: "A new question has been received", and the email contains a link that leads to an html page (approve_question.html). Up to here everything works. However, the link only leads to an empty html page. I want added question then show on approve_question.html so admin can save in database after check so question will show in game then. my problem is i can't find question.html page (the question with four answers can then be entered here), with the content forward to approve_question.html. I'll add some more code to make it clearer. The question.html has one field for the questions and four for the answers. I would like to fill … -
While paginating my results of dictionary values in djnago I am getting an error as unhashable type: 'slice'
I am trying to paginate my results(dictionary values) to html page. While doing I am getting an error unhashable type: 'slice' views.py from django.shortcuts import render import urllib.request import json from django.core.paginator import Paginator def display(request): cities=['vijayawada','guntur','tenali','rajahmundry','amaravathi','Bengaluru','Mangaluru','Chikkamagaluru','Chennai'] data = {} for city in cities: source = urllib.request.urlopen( 'https://api.openweathermap.org/data/2.5/weather?q=' + city + '&units=metric&appid=APIID').read() list_of_data = json.loads(source) data[city] = { "country_code": str(list_of_data['sys']['country']), "coordinates": { 'latitude': str(list_of_data['coord']['lat']), 'longitude': str(list_of_data['coord']['lon']) }, "temp": str(list_of_data['main']['temp']) + ' °C', "pressure": str(list_of_data['main']['pressure']), "humidity": str(list_of_data['main']['humidity']), 'main': str(list_of_data['weather'][0]['main']), 'description': str(list_of_data['weather'][0]['description']), 'icon': list_of_data['weather'][0]['icon'], } p = Paginator(data,3) page = request.GET.get('page') d = p.get_page(page) context = {'data': d} return render(request, 'display.html', context) Please help me to paginate the values in a dictionary I expect the paginated results of my dictionary values -
How do I override internal Django Installed app settings.py parameter
I am using django-otp via django-two-factor-auth and I am unable to override a very simple setting in settings.py that the django-otp package is requiring. Internally I can see that the django-otp is requesting OTP_TOTP_ISSUER to be set in the hosting app's settings.py. But for some reason, seems that the django-otp package is relying on some internal settings.py maybe also because the django-otp have internal "plugins" which are installed as apps in my django app. Trying to override their data seems to be futile... Any idea how can a setting be injected/overridden in internal "installed_app"? -
Find a get queryset values that existes in another queryset of tha same model
Iam tring filter permission queryset that exists in another Queryset of permission. How can filter that Queryset ####### My code staff_perm = instance.permissions.all(). designation_perms = instance.designation.permissions.all() # needed_designation_perms = designation_perms that exists in staff_perm Ex : Consider A and B are Querysets A = [1,2,3,4,5] B = [1,3,5,7,9] i want C = [1,2,3,4,5] -
Defining custom request - Swagger (Drf-yasg)
I have a use case, where the request required fields are different depending on one of the field value of the request. Example, if the value of move type in request is 'P', then some fields are mandatory, otherwise if value of move type is 'D', then some of the other fields are mandatory. How to create custom request for such use case using drf-yasg ? -
How to make API for filtering objects in django based on multiple key-value pairs in GET request?
I have an API url in "urls.py" folder of my django project :- path('tests/filter/<str:key1>/<str:value1>', FilterTests.as_view()) This works fine for the below code :- from rest_framework import generics from service.models import Test from service.serializers import TestListSerializer class FilterTests(generics.ListAPIView): queryset = Test.objects.all() serializer_class = TestListSerializer def get_queryset(self, *args, **kwargs): key1 = self.kwargs['key1'] value1 = self.kwargs['value1'] return Test.objects.filter(**{key1: value1}) The above code filters my Test objects based on only a single key value-pair passed in the get request. I now want to filter on a more than 1 key-value pairs. Eg:- Filter should be : name=john&type_test=algo&count=3 How should I design the api endpoint in django and not make the url too lengthy as well? Can I use a json or map, via request body? I am a beginer to django and api development so any help would be appreciated. -
How to publish app with Django React Native
This is my first time to deploy my app to app store. However, I cannot find the way to deploy Django and React Native app. Do I have to deploy separately? or possible deploy both at same time? Like using EAS or others? I tried EAS but Django file not located inside React Native Expo file. Do I have to move Django file inside expo file? -
How to display in the django template information of a manytomany model
I am practicing django but i am not able to display the following information from the database in the template. I have these 3 models (PURCHASE ORDERS, MOVEMENTS, RECEIPTS): class Ordenes_Compra(models.Model): orden_compra=models.IntegerField(primary_key=True) proveedor=models.ForeignKey(Proveedores, on_delete=models.CASCADE) comedor=models.ForeignKey(Centros, on_delete=models.CASCADE) fecha_documento=models.DateField() fecha_entrega=models.DateField() class Meta(): verbose_name='Orden de compra' verbose_name_plural="Ordenes de compra" class Movimientos(models.Model): movimientos = \[ ('ING', 'INGRESO'), ('SAL', 'SALIDA'), \] estados = \[ ('PRO', 'PROCESADO'), ('ANA', 'ANALIZADO'), ('PEN', 'PENDIENTE'), ('CAN', 'CANCELADO'), \] cantidad_um=models.DecimalField(decimal_places=3, max_digits=20) precio_por_um=models.DecimalField(decimal_places=3, max_digits=20) mat_um=models.ForeignKey(Materiales, on_delete=models.CASCADE, editable=True) orden_compra_mov=models.ForeignKey(Ordenes_Compra,on_delete=models.CASCADE) tipo_movimiento=models.CharField(max_length=3, choices=movimientos, blank=True, null=True) estado_movimiento=models.CharField(max_length=3, choices=estados, blank=True, null=True) class Meta(): verbose_name='Movimiento' verbose_name_plural="Movimientos" class Imagenes_Comprobantes_Moviemientos (models.Model): imagen_factura=models.ImageField(null=True, blank=True) factura=models.CharField(max_length=20) orden_compra_imagen=models.ManyToManyField(Ordenes_Compra) class Meta(): verbose_name='Comprobante' verbose_name_plural="Comprobantes" Each PURCHASE ORDER can have several RELATED VOUCHERS and several VOUCHERS can have different PURCHASE ORDERS. In the template, I am going to show a table with the MOVEMENTS, from which I want to give the information of the PURCHASE ORDERS that are related to that movement and the PROOFS related to that PURCHASE ORDERS: I was thinking of something like this, but it doesn't work and I'm totally lost in what would be the best way to obtain the information of the receipts related to the purchase order related to the movement in the template: THE SECOND FOR IS THE … -
Auto Increment in child model
models.py class Pallet_Mission(models.Model): code = models.AutoField(primary_key=True) load_type = models.CharField(max_length=20,null=True,blank=True) mission_no = models.CharField(max_length=255, null=True,blank=True) class PalletSubMission(models.Model): mission_id = models.CharField(max_length=255,null=True,blank=True) pallet_mission = models.ForeignKey(Pallet_Mission,on_delete=models.CASCADE,related_name='sub',null = True) point = models.CharField(max_length=255,null=True,blank=True) i have a parent and child model look like this. and my output look something like this "code": 52, "mission_no": "test1234", "load_type": "1234", "sub": [ { "id": 75, "mission_id": "s1", "point": null, "pallet_mission": 52 }, { "id": 76, "mission_id": "s2", "point": null, "pallet_mission": 52 } ], } Now my 'mission_id" are inserted manually. I want my child model's "mission_id" to be like auto increment like shows 's1' for the first data 's2' for the second data and so on . And it will reset in another set of data -
Error: 'QuerySet' object has no attribute '_meta'
When calling the update API i and getting this Error: 'QuerySet' object has no attribute '_meta' Please have a look at my code, not sure where i am going wrong. models.py class FarmerAdvisory(models.Model): ''' Farmer Advisory model definition ''' CATEGORY_CHOICES = ( ("CROP", "CROP"), ("WEATHER", "WEATHER"), ("FARMLAND", "FARMLAND") ) SUB_CATEGORY_CHOICES = ( # ("CROP", "CROP"), # ("WEATHER", "WEATHER"), # ("FARMLAND", "FARMLAND") ) STATUS_CHOICES = ( ('OPEN', 'OPEN'), ('IN-PROGRESS', 'IN-PROGRESS'), ('CLOSED', 'CLOSED') ) id = models.AutoField(db_column='id', primary_key=True) category = models.CharField(db_column='category', max_length=100, null=False, blank=False, choices=CATEGORY_CHOICES) sub_category = models.CharField(db_column='sub_category', max_length=100, null=False, blank=False) # ,choices=SUB_CATEGORY_CHOICES) title = models.CharField(db_column='title', max_length=200, null=True, blank=True) description = models.CharField(db_column='description', max_length=500, null=True, blank=True) media = models.JSONField(db_column='media', blank=True, null=True) status = models.CharField(db_column='status', max_length=15, null=False, blank=False, default='OPEN', choices=STATUS_CHOICES) # assigned_to = reply = models.CharField(db_column='reply', max_length=500, null=True, blank=True) reply_media = models.JSONField(db_column='reply_media', blank=True, null=True) label = models.CharField(db_column='label', max_length=100, null=True, blank=True) farmer_id = models.ForeignKey(Farmer, on_delete=models.CASCADE, db_column='farmer_id') objects = models.Manager() class Meta: managed = True db_table = 'farmer_advisory' serializers.py class FarmerAdvisorySerializer(serializers.ModelSerializer): class Meta: model = FarmerAdvisory fields = '__all__' views.py class FarmerAdvisoryObjectView(ShortCircuitMixin, APIView): def put(self, request, farmer_id, adv_id): try: farmer_adv = FarmerAdvisory.objects.filter(farmer_id=farmer_id, id=adv_id) serializer = FarmerAdvisorySerializer(farmer_adv, data=request.data) if serializer.is_valid(raise_exception=True): serializer.save() response = JsonResponse(serializer.data, status=status.HTTP_201_CREATED) return response return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) except Exception as ex: logger.error(traceback.format_exc()) return Response(data={"Error": … -
How to remove similar and duplicate queries in django rest framework?
When i call product endpoint, duplicate and similar queries are occured for average rating. I have used prefetch_related to solve the problem but it seems like the way i used arenot correct. Can you guys please help me to solve this scenario. Here is the model structure models.py class Product(models.Model): name = models.CharField(max_length=255) vendor = models.ForeignKey( Vendor, on_delete=models.CASCADE, ) class ProductRating(models.Model): product_id = models.ForeignKey( Product, on_delete=models.CASCADE, ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) maxval=5 message='Rating must be less than 5' rate =models.PositiveIntegerField(validators=[MaxValueValidator(maxval,message)],null=True) comment = models.TextField(blank=True,null=True) seller_reply = models.TextField(blank=True,null=True) reply_at=models.DateTimeField(auto_now=True) created_at=models.DateTimeField(auto_now=False,auto_now_add=True) class VendorRating(models.Model): product_id = models.ForeignKey( Product, on_delete=models.CASCADE, ) vendor_id=models.ForeignKey( Vendor, on_delete=models.CASCADE ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) maxval=5 message='Rating must be less than 5' communication_rate=models.PositiveIntegerField(validators=[MaxValueValidator(maxval,message)],null=True,blank=True) product_quality_rate=models.PositiveIntegerField(validators=[MaxValueValidator(maxval,message)],null=True,blank=True) experience_rate=models.PositiveIntegerField(validators=[MaxValueValidator(maxval,message)],null=True,blank=True) created_at=models.DateTimeField(auto_now=False,auto_now_add=True) in views.py def get_queryset(self): queryset=self.get_serializer().setup_eager_loading(Product.objects.all()) return queryset in serializers.py class ProductSerializer(TaggitSerializer, serializers.ModelSerializer): avg_productrating = serializers.SerializerMethodField("get_rating") avg_vendorrating=serializers.SerializerMethodField("get_avgvendorrating") def get_rating(self, obj): rating=obj.productrating_set.all().aggregate(avg=Avg("rate"))['avg'] average_rate=round(rating,2) if rating else rating return average_rate def get_avgvendorrating(self,obj): try: average_rate=obj.vendor.vendorrating_set.all().aggregate( Avg("communication_rate"),Avg('product_quality_rate'),Avg("experience_rate") ) rates=[rate for rate in average_rate.values() if rate is not None] if(not rates): total=0 else: total=sum(rates)/3 return round(total,2) except: return 0 @staticmethod def setup_eager_loading(queryset): """ Perform necessary eager loading of data. """ queryset=queryset.prefetch_related(Prefetch('vendor',queryset=Vendor.objects.prefetch_related('user','vendorrating_set'))) in urls.py rom rest_framework import routers from . import views router = routers.SimpleRouter() router.register(r"product", views.ProductViewSet,basename='products') output … -
Validate keys and value types in Django .JSONFields
Problem Statement I have a Django model containing a JSONField: class DataModel(models.Model): dict_field = models.JSONField() How can I validate the inputs of this JSONField such that it only accepts a pre-defined list of keys and their associated types, as follows: "key1": bool "key2": int "key3": Optional[int] My Attempt I attempted to solve this with Pydantic by defining a class: class DictModel(pydantic.BaseModel): key1: bool key2: int key3: Optional[int] But I couldn't find a way to pass this schema to my Django model. Does django have something built in for this type of problem? -
how to connect postgresql database using IP Address in python
I want to connect my posgresql database using remote ip address but i am getting an error. psycopg2.OperationalError: connection to server at "178.56.25.266", port 5432 failed: Connection refused (0x0000274D/10061) Is the server running on that host and accepting TCP/IP connections? here also i am sharing my python code. import psycopg2 conn = psycopg2.connect(database="test", user='postgres', password='', host='178.56.25.266') cursor = conn.cursor() cursor.execute("select version()") data = cursor.fetchone() print("Connection established to: ",data) conn.close() Please help me to resolve this problem. -
Django project doesn't work on the VPS with a port, gunicorn+ nginx
I have Django project on my VPS. When I check my website in the browser I get an error: 1 connect() failed (111: Connection refused) while connecting to upstream, client: 86.245.120.83, server: mysite.com, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:6112/", host: "mysite.com" upstream app_server_wsgiapp { server 127.0.0.1:6112 fail_timeout=0; } server { server_name mysite.com www.mysite.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { autoindex on; alias /var/www/www-root/data/www/mysite.com/public_html/static/; } location /media/ { alias /var/www/www-root/data/www/mysite.com/public_html/media/; } location / { include proxy_params; proxy_pass http://app_server_wsgiapp; } charset off; disable_symlinks if_not_owner from=$root_path; include /etc/nginx/vhosts-includes/*.conf; include /etc/nginx/vhosts-resources/mysite.com/*.conf; access_log /var/www/httpd-logs/mysite.com.access.log; error_log /var/www/httpd-logs/mysite.com.error.log notice; set $root_path /var/www/www-root/data/www/mysite.com; root $root_path; listen XX.XXX.XX.XXX:80; } /etc/systemd/system/mysite.service [Unit] Description=mysite daemon Requires=mysite.socket After=network.target [Service] User=www-root Group=root WorkingDirectory=/var/www/www-root/data/www/mysite.com/public_html/sokovblogpr ExecStart=/var/www/www-root/data/www/mysite.com/public_html/mysiteenv/bin/gunicorn --bind 0.0.0.0:6112 mysitepr.wsgi:application [Install] WantedBy=multi-user.target /etc/systemd/system/mysite.socket [Unit] Description=sokovblog socket [Socket] ListenStream=/run/mysite.sock [Install] WantedBy=sockets.target systemctl status mysite ● mysite.service - mysite daemon Loaded: loaded (/etc/systemd/system/mysite.service; enabled; vendor preset: enabled) Active: active (running) since Wed 2022-12-07 18:54:42 CET; 16min ago TriggeredBy: ● mysite.socket Main PID: 4360 (gunicorn) Tasks: 2 (limit: 1843) Memory: 45.1M CGroup: /system.slice/mysite.service I checked it works if I start it in the terminal via Gunicorn gunicorn --bind 0.0.0.0:6112 mysitepr.wsgi And if I check it in terminal I get my main html page … -
How can I store clone of the image to another model on Django
Does anyone know how to store a clone of the original image to another model on Django. This is my models.py file class blogs(models.Model) title = models.CharField(max_length=100, null=True, blank=True) slug = models.SlugField(max_length=200, unique=True, auto_created=True) author = models.ForeignKey(User, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) time = models.TimeField(auto_now_add=True) cone_image = models.ImageField(upload_to='cloned') image = models.ImageField(upload_to='photos',height_field="image_height", width_field="image_width" I am looking to clone the image field in this model and store to clone image model -
Sync to Async Django ORM queryset length
In asynchronous context I try to do: invites = await InviteLogic.get_invites(self.app.user) if len(invites) > 0: ... InviteLogic is like this: @sync_to_async def get_invites(self, inviter): return Invite.objects.filter(inviter=inviter) I get an error in line if len(... django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. How do I call len asynchronously? -
Object type <class 'str'> cannot be passed to C code in AES CTR
I want to encrypt with AES ctr in Python, but I get an error: Object type <class 'str'> cannot be passed to C code I was trying code from tweaksp using code. All I want is just to encrypt the plaintext. Here's my code: key_bytes = 16 def encrypt(key, pt): pt = read_file(pt) if len(key) <= key_bytes: for x in range(len(key),key_bytes): key = key + "0" assert len(key) == key_bytes print(key) print(pt) # Choose a random, 16-byte IV. iv = Random.new().read(AES.block_size) # Convert the IV to a Python integer. iv_int = int(binascii.hexlify(iv), 16) print(iv_int) # Create a new Counter object with IV = iv_int. ctr = Counter.new(AES.block_size * 8, initial_value=iv_int) print(ctr) ctr2 = ctr.encode('utf8') # Create AES-CTR cipher. aes = AES.new(key.encode('utf8'), AES.MODE_CTR, counter=ctr2) print(aes) # Encrypt and return IV and ciphertext. ciphertext = aes.encrypt(pt) return (iv, ciphertext) def read_file(f): f = open('media/txt/'+f, 'r') f.read() f.tell() f.seek(0) file_content = f.read() f.close() return file_content And my traceback: Traceback (most recent call last): File "C:\Users\Capoo\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Capoo\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "F:\KULIAH\SEMESTER8\SKRIPSI\MusicLockApp\MusicLockApp\views.py", line 54, in homepage (iv, enc) = encrypt(ky, pt) File "F:\KULIAH\SEMESTER8\SKRIPSI\MusicLockApp\MusicLockApp\views.py", line 268, in encrypt ciphertext = aes.encrypt(pt) … -
Django nested serializers - Direct assignment to the reverse side of a related set is prohibited
I want to implement my own create function on my serializer but I'm getting the following error: Internal Server Error: /api/cheatsheets/ Traceback (most recent call last): File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/rest_framework/mixins.py", line 19, in create self.perform_create(serializer) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/rest_framework/mixins.py", line 24, in perform_create serializer.save() File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/rest_framework/serializers.py", line 212, in save self.instance = self.create(validated_data) File "/home/christian-sama/Code/cheatsheet-app/api/serializers.py", line 35, in create Section.objects.create(cheatsheet=cheatsheet, **section) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/django/db/models/query.py", line 669, in create obj = self.model(**kwargs) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/django/db/models/base.py", line 562, in __init__ _setattr(self, prop, value) File "/home/christian-sama/Code/cheatsheet-app/venv/lib/python3.10/site-packages/django/db/models/fields/related_descriptors.py", line 595, in __set__ raise TypeError( TypeError: Direct assignment to the reverse side of a related set is prohibited. Use lines.set() instead. My models.py from django.db import models class Cheatsheet(models.Model): title = models.CharField(max_length=500) description = models.CharField(max_length=500) score = models.IntegerField() … -
How to resolve django filter button not working?
I am trying to implement Django Filtering but I cant seem to make it work. Only an 'Option' button appears the 'filter' button does not. It still does not work. What seems to be the problem here? views.py class MKRealtyListView(generics.ListAPIView): queryset = Realty.objects.all() serializer_class = RealtySerializer filter_backends = [DjangoFilterBackend] filterset_fields = ('type', 'location') #@permission_classes([IsAuthenticated]) @api_view(['GET', 'POST']) def listings(request, format=None): if request.method == 'GET': realty = Realty.objects.all() serializer = RealtySerializer(realty, many=True) return Response(serializer.data) settings.py INSTALLED_APPS = [ 'rest_framework', 'mkrealty', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework.authtoken', 'django_filters' ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend',] } urls.py urlpatterns = [ path('admin/', admin.site.urls), path('listings/', views.MKRealtyListView.listings), path('listings/<int:id>', views.listing_detail), path('api-token-auth/', obtain_auth_token, name='api_token_auth'), # <-- And here ] -
How to construct dynamic Q() in Django
I'm trying to filter dynamic value from a form in template to my query in Django project the value can be dynamic, but it would look like this first_query = ['a', 'b', 'c'] second_query = ['d', 'e', 'f'] what i want to achieve is to query something like this SELECT * FROM table WHERE column_1 = 'a' OR column_1 = 'b' OR column_1 = 'c' OR column_2 = 'd' OR column_2 = 'e' OR column_2 = 'f' Here's what i've done first_query = [ Q(column_1__contains=w) for w in first_query ] """ If you print first_query [<Q: (AND: ('column_1__contains', 'a'))>, <Q: (AND: ('column_1__contains', 'b'))>, <Q: (AND: ('column_1__contains', 'c'))>] """ reduce_first_query = reduce(or_, query_first_query) """ (OR: ('column_1', 'a'), ('column_1', 'b'),('column_1', 'c')) """ second_query = [ Q(column_2__contains=w) for w in second_query ] reduce_second_query = reduce(or_, query_second_query) When i try to filter Item from my database it gives me rows more than doubled than what i do directly from the database test_item = Item.objects.filter(reduce_first_query) # Gives 1900 ish rows, should be 900 ish What do i do wrong, is it because of the way i construct Q() ? or there other mistake ? NOTES I'm using Postgresql 14 -
How to address this codec error when fetching an api for image upload in django?
Error: UnicodeDecodeError at /user_image_upload/ 'utf-8' codec can't decode byte 0xcc in position 144: invalid continuation byte Payload: Image (binary) 500 internal server error. VueJS method/data...: data(){ return { profile_image:null } }, async createImage() { let received_image = document.querySelector('#imageInput').files[0] let formData = new FormData // 'image' as in models.py formData.append('image', received_image) fetch('/user_image_upload/',{ method:'POST', credentials: 'include', body: formData }).then(response => response.json()).then((data) => this.profile_image=(data)) console.log(this.profile_image) }, In Django template: {% csrf_token %} <form @submit.prevent=""> {% csrf_token %} <input id ="imageInput" type = "file" accept="image/"> <button @click="createImage()">Upload</button> </form> in models.py class Profile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) image = models.ImageField(upload_to='uploads') def __str__(self): return f'{self.user.username} Profile' in views.py @login_required @csrf_exempt def user_image_upload(request): if request.method=='POST': response = json.loads(request.body) Item.objects.create(user=request.user) return JsonResponse({'new':'updated'}) -
Django - How to change Textarea rows and columns in media query
I am having difficulties trying to understand how to change Textarea sizes so that my webpage is responsive. I currently have it set where the rows are 8 and cols is 60 which is perfect for viewing a webpage on a desktop. However, as i am trying to make my webpage responsive, i can not find a way to change the column value down to 30. I have thought about using css media query for this but can not understand how to change the values as they are currently set in the forms.py file as as shown below. I know users are able to resize the Textarea but i would like it if they can not resize the text area. So my question is if it is possible to make the Textarea responsive? forms.py: class UserSettings(ModeldForm): class Meta: model = Profile fields = ["name", "email", "profile_biography"] widgets = { 'profile_biography': forms.Textarea(attrs={ 'rows': 8, 'cols': 60, 'style':'resize:none'}), }