Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to server static files Django S3
I'm trying to put static files to S3, and here's what I have so far in settings.py: # AWS S3 Static Files Configuration AWS_ACCESS_KEY_ID = config('AWS_S3_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_S3_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_S3_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = 'public-read' AWS_LOCATION = 'static' AWS_DEFAULT_ACL = None STATICFILES_DIRS = [ 'pakcage404/static', ] STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_REGION_NAME = 'ca-central-1' AWS_S3_USE_SSL = False AWS_S3_ENDPOINT_URL = f"https://{AWS_STORAGE_BUCKET_NAME}.s3.ca-central-1.amazonaws.com" AWS_S3_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.ca-central-1.amazonaws.com/{AWS_STORAGE_BUCKET_NAME}" But when I try to access one of the static files I have uploaded, I was given this error message on the browser: <Error> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>some request ID</RequestId> <HostId>some ID</HostId> </Error> -
How to annotate related table in django?
I have two entities Task and Technology. Technology table has a FK to Task and each task has 9 technologies. enabled category frequency c1 c2 c3 note True 3G 2100 11/03/2010 foo False 4G 700 02/04/2012 bam False 4G 1800 spam True 4G 2100 bim True 4G 2600 bum True 5G 700 tan False 5G 3700 tan True 5G 26000 tan For each tasks I need to annotate a cell of this technology matrix. This means annotate something like: candidates_technologies__3G_2100_enabled candidates_technologies__3G_2100_c1 candidates_technologies__3G_2100_c2 candidates_technologies__3G_2100_c3 candidates_technologies__3G_2100_note candidates_technologies__4G_700_enabled candidates_technologies__4G_700_c1 candidates_technologies__4G_700_c2 candidates_technologies__4G_700_c3 candidates_technologies__4G_700_note candidates_technologies__4G_1800_enabled candidates_technologies__4G_1800_c1 candidates_technologies__4G_1800_c2 candidates_technologies__4G_1800_c3 candidates_technologies__4G_1800_note ... Where candidates_technologies is the related name. Currently this is my solution, but is killing the performance. from django.db.models import Q, F, Value, Case, When, DateField, BooleanField, CharField bool_cols, text_cols = ["enabled"], ["onair_note"] date_cols = [t for t in TECHNOLOGY_COLUMNS if t not in text_cols or t not in bool_cols] columns = date_cols + bool_cols + date_cols def _get_output_field(col): if col in bool_cols: return False, BooleanField() elif col in text_cols: return "", CharField() else: return None, DateField() tech_annotations, whens = {}, [] for category, frequency in TECHNOLOGY_FREQUENCY_LIST: for column in columns: out = _get_output_field(column) key = '_'.join([category, frequency, column]) value = ExpressionWrapper( Case( When( Q(**{'candidates_technologies__category': category}) … -
Change background color in a select option dropdown
I'm rendering a form using django. One of the fields in the form is a select with options. Rendering form field: {{ form.work }} The select options after rendering are: <select name="work" class="form-control" required="" id="id_work"> <option value="" selected="">---------</option> <option value="chair">The chair</option> <option value="table">The table</option> </select> How can i change the background color for each of the values? So when i press the dropdown arrow to see all values with different colors. I used css with no success. select option[value="chair"] { background-color: red !important; } select option:nth-child(2) { background: red; } As a note, the form consists of different fields with select options. I use bootstrap 4. Thank you -
I am getting 'BasePermissionMetaclass' object is not iterable when trying to access the api
I am trying to access the api i made but i keep getting this 'BasePermissionMetaclass' object is not iterable error views.py class BlogPostListView(ListAPIView): queryset = BlogPost.objects.order_by('-date_created') serializer_class = BlogPostSerializer Lookup_field = 'slug' permission_classes = (permissions.AllowAny, ) class BlogPostDetailView(RetrieveAPIView): queryset = BlogPost.objects.order_by('-date_created') serializer_class = BlogPostSerializer Lookup_field = 'slug' permission_classes = (permissions.AllowAny, ) class BlogPostFeaturedView(ListAPIView): queryset = BlogPost.objects.all().filter(featured = True) serializer_class = BlogPostSerializer Lookup_field = 'slug' permission_classes = (permissions.AllowAny, ) class BlogPostCategoryView(APIView): serializer_class = BlogPostSerializer permission_classes = (permissions.AllowAny, ) def post(self, request, format=None): data = self.request.data category = data['category'] queryset = BlogPost.objects.order_by('-date_created').filter(category__iexact = category) serializer = BlogPostSerializer(queryset, many=True) return Response(serializer.data) In settings.py i have : REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ] } I havetried everything i can think of but not been able to fix it -
How to update stock through purchase and sale in Django?
I am working on a Django Billing Webapp/Invoicing Webapp. I'm having a problem updating stocks through Purchase and Sales. I want the medicine quantity to increase when there is a purchase and decrease when there is a sale. But after a lot of tries, I cannot achieve it. Please help me to integrate this feature into my Django WebApp. Here are the contents of the files: Models.py from django.db import models from django.utils import timezone from django.shortcuts import render, get_object_or_404 #------------------------Medicine models---------------------------------- gst = ( (0, '0%'), (5, '5%'), (12, '12%'), (18, '18%'), ) # Create your models here. class Medicines(models.Model): Med_HSN = models.IntegerField(default=0) Med_name = models.CharField(max_length=20) Med_Quantity = models.IntegerField(default=0) Med_Manufacturer = models.CharField(blank=True,max_length=50) Med_Expiry = models.CharField(default=1,max_length=10) Med_Batch_no = models.CharField(blank=True,max_length=15) Med_MRP = models.FloatField(blank=False) Med_Rate = models.FloatField(blank=False) Med_GST = models.IntegerField(default=0,choices=gst) date_created = models.DateField(default=timezone.now) def caluclate_value(self): value = self.Med_MRP * (self.Med_GST/100) total_value = self.Med_MRP + value return total_value def get_cost(self): return self.caluclate_value() * self.Med_Quantity def __str__(self): return self.Med_name + " : " + str(self.caluclate_value()) # def caluclate_stock(self): # med_quantity = self(request=self.request).Med_Quantity # get_med_1_quantity = Purchase.med_quantity_1 # value = med_quantity + get_med_1_quantity # print(value) # return value #----------------------------------End Medicines Models-------------------------------------- #---------------------------------Sales Models-------------------------------- from django.core.checks import messages from django.db import models from Customer.models import Customer … -
Expire/Invalidate Session from all browsers except current
I have a django application that is using cookie-based sessions. I have a use-case where, after user changes the password, I update the session using update_session_auth_hash(request, request.user). The problem is when I have logged in from 2 different browsers and I update the password from one browser, it automatically updates the session in other browser. What I want is that, when I change the password in one browser, it should update the session on that browser only and remove/invalidate session from all other browsers. -
Django rest Framework error messages. Does not work
I am new to Django and I am working on a small project, I want an error message to be shown if the user let the field empty. the code that I wrote is not working. Can anyone help me ? def validate_name(school: School): if school.name is None: raise APIException(detail='Name is mandatory.') class SchoolService(object): @staticmethod def validate_create(school: School): validate_name(school) -
Cannot access local django webserver
I cannot seem to figure out why I cannot access my local django webserver from an outside device. I suspect it has to do with port forwarding but none of my attempts to solve it seem to work. I started by following the suggestions posted here How to access the local Django webserver from outside world by launching the server using python manage.py runserver 0.0.0.0:8000 and by entering <my-ip-address>:<port> in my external device' browser. This did not work, so I tried to explicitly make sure port forwarding was enabled by adding the following lines to iptables. iptables -A INPUT -p tcp --dport 8000 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT iptables -A OUTPUT -p tcp --sport 8000 -m conntrack --ctstate ESTABLISHED -j ACCEPT netfilter-persistent save Still, I'm not able to access the local webserver. No error messages show up, the browser just tells me that the address took too long to respond. I've tried to do the above but this time with port 80 and using sudo when needed without avail. In addition I've tried to use this line ALLOWED_HOSTS = ['*'] as suggested by multiple users. I've tried to investigate whether the application is really running on the indicated port … -
How to uncensor passwords in Django Admin page?
I'm creating an admin page for a Cybersecurity project. In admin page's users, a user profile should show the password in uncensored format, such as abcdefghijklmn, but it shows as abc***********. I need to uncensor it. In sqlite3, it is stored in the hashed format. -
'' takes 1 positional argument but 2 were given django
mi codigo parece funcionar, cuando pongo mal el usuario o la contraseña me funciona el mensaje de error, sin embargo cuando quiero ingresar realmente a la pagina oculta, me arroja lo siguiente: TypeError at /administracion/ingreso login_oculto() takes 1 positional argument but 2 were given Request Method: POST Request URL: http://localhost:8000/administracion/ingreso?next=/oculto Django Version: 3.2.8 Exception Type: TypeError Exception Value: login_oculto() takes 1 positional argument but 2 were given Exception Location: C:\Users\OGT\Museum\mu2\views.py, line 48, in login_oculto Python Executable: C:\Users\OGT\AppData\Local\Programs\Python\Python310\python.exe Python Version: 3.10.0 Python Path: ['C:\Users\OGT\Museum', 'C:\Users\OGT\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\OGT\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\OGT\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\OGT\AppData\Local\Programs\Python\Python310', 'C:\Users\OGT\AppData\Local\Programs\Python\Python310\lib\site-packages'] . . . dejo mi codigo de views, urls y html, por favor ayudenme login.html <div class="contenedor_formulario"> {% if error %} <p style="color: black;">{{ error }}</p> {% endif %} <form action="" method="POST" style="text-align: center;"> {% csrf_token %} <table class="tabla_formulario"> <form method="POST" action="{% url 'anyname' %}"></form> <input type="text" placeholder="Usuario" name="username" /> <input type="password" placeholder="contraseña" name="password" /> </table> <input class="boton_formulario" type="submit" value="Ingresar"> </form> </div> urls.py urlpatterns = [ path('administracion/ingreso', views.login_oculto, name='anyname'), path('oculto', views.oculto,name='oculto') ] views.py def login_oculto(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') usuario = authenticate(request, username = username, password = password) if usuario: login_oculto(request, usuario) return redirect('oculto') else: return render (request, 'mu2/login.html', {'error': 'usuario o contraseña incorrecta'}) return render(request, … -
Django iterate on values()
I have somethink like this: vmware = Vmware.objects.values('pk', 'hostname') the result : <QuerySet [{'pk': 1, 'hostname': 'ste1vvcsa'}, {'pk': 3, 'hostname': 'ste1vvcsatest'}]> I want to iterate on it and retreive the values of pk and hostname I have an error when I do somethink like this: for i in vwmare: print(i.hostname) Error : AttributeError: 'dict' object has no attribute 'hostname' -
Django-tables2: How can I add columns based on a queryset that can change
I have a table created in django tables2 which displays related fields of my model queryset. However there is a many-to-many field and I would like to display each object as a column. Obviously this is variable, so I can't hard code this into the table columns like I would with the other fields. One option is to put all M2M objects into the same column, but this could get quite messy (i am not envisaging this being >3 M2M links in total, so separate cols would be best). I've managed to use the init method of the table to get a new col for each link, however I'm struggling with how to actually get the data i need into it.. models: class GenomeBuild(models.Model): build_name = models.CharField(max_length=6) in_use = models.BooleanField(default=False) def __str__(self): return f"{self.build_name}" class Variant(models.Model): chromosome = models.CharField(max_length=2) genomic_location = models.CharField(max_length=50) ref = models.CharField(max_length=1024) alt = models.CharField(max_length=1024) var_type = models.CharField(max_length=60) class Meta: db_table = "variant" unique_together = ( ("chromosome", "genomic_location", "ref", "alt",),) def __str__(self): return variant_str_formatting(variant=self) @property def vNomen(self): return vNomen_str(variant=self) class VariantBuild(models.Model): variant_id = models.ForeignKey( Variant, on_delete=models.CASCADE, db_column="variant_id", related_name="variant_id" ) build_id = models.ForeignKey( GenomeBuild, on_delete=models.CASCADE, db_column="build_id", ) def __str__(self): return f"{self.variant_id} ({self.build_id})" class VariantGeneTranscript(models.Model): variant_builds = models.ManyToManyField( VariantBuild, … -
Django, SFTP storage file handling problem
I am using django-storages in my project. The use case: I upload a file from a vue app. My server side(with django rest framework) handle this request and upload the file(I want to upload images and videos, so png and mp4, mostly). My file model: from django.db import models from storages.backends.sftpstorage import SFTPStorage SFS = SFTPStorage() class File(models.Model): class Meta: verbose_name_plural = "File" name = models.CharField(max_length=255) location = models.CharField(max_length=255) uploadDate = models.DateField() comment = models.CharField(max_length=255, null=True, blank=True) connectedTo = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True) ghbwrzipgw = models.FileField( null=True, blank=True, storage=SFS) def __str__(self): return f'{self.name} (Upload Date: {self.uploadDate}, Connected To: {self.connectedTo})' My file view: from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from measurement_db.models.file import File from measurement_db.serializers.file import FileSerializer @api_view(['GET']) def FileList(request): file = File.objects.all() serializer = FileSerializer(file, many=True) return Response(serializer.data) @api_view(['GET']) def FileDetail(request, pk): file = File.objects.get(id=pk) serializer = FileSerializer(file, many=False) return Response(serializer.data) @api_view(['POST']) def FileCreate(request): serializer = FileSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['PUT']) def FileUpdate(request, pk): file = File.objects.get(id=pk) serializer = FileSerializer(instance=file, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['DELETE']) def FileDelete(request, pk): file = File.objects.get(id=pk) file.delete() return Response(status=status.HTTP_200_OK) And a snippet from my settings.py: DEFAULT_FILE_STORAGE … -
How to implement selection with pre-sorting in Django?
In the database, there is a table with two columns: 'City' and 'Post Office'. How to implement branch selection with pre-sorting by 'City'? I have absolutely no ideas, I would be grateful for any tips. -
I cant figure out how to add my "et" object to the group , i keep getting this error "'Group' object has no attribute 'et_set'
def etudiant_inscription(request): form = form_etudiant() if request.method == 'POST': form = form_etudiant(request.POST) if form.is_valid(): et = form.save() et.save() group = Group.objects.get(name="etudiant") group[0].et_set.add(et) return HttpResponseRedirect('/etudiant_login') else: return HttpResponseRedirect('/accueil') return render(request,'etudiant_inscription.html',{'form':form}) Traceback (most recent call last): File "C:\Users\Mega-PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Mega-PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Mega-PC\OneDrive\Desktop\testtttt\app\views.py", line 50, in etudiant_inscription group[0].et_set.add(et) Exception Type: AttributeError at /etudiant_inscription/ Exception Value: 'Group' object has no attribute 'et_set' """ what am i doing wrong exactly ? -
POST request returning 401 Unauthorised (only in Chrome)
I'm using Django Rest Framework and Vue.js to build a basic web app, and am currently working on the auth. Using axios to send a post request while registering a new user returns 401 in Chrome for some reason, but works in other browsers (Edge) and returns a 201 Created. The error in chrome is "detail: Invalid Token", but this particular endpoint (registration) doesn't even need auth/token to access. My frontend is at http://192.168.1.33:8080 and my backend is at http://127.0.0.1:8000 I am trying to POST data to http://127.0.0.1:8000/api/v1/users/auths/ The Network tab in chrome dev tools after trying a request: Request URL: http://127.0.0.1:8000/api/v1/users/auths/ Request Method: POST Status Code: 401 Unauthorized Remote Address: 127.0.0.1:8000 Referrer Policy: strict-origin-when-cross-origin Access-Control-Allow-Origin: http://192.168.1.33:8080 Allow: GET, POST, HEAD, OPTIONS Content-Length: 27 Content-Type: application/json Date: Mon, 06 Dec 2021 12:19:15 GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.8.5 Vary: Accept, Origin WWW-Authenticate: Token X-Content-Type-Options: nosniff X-Frame-Options: DENY Accept: application/json, text/plain, */* Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 Authorization: Token acf8b9099de5eba413dea141ce2c06b6cfb03159 Connection: keep-alive Content-Length: 53 Content-Type: application/json Host: 127.0.0.1:8000 Origin: http://192.168.1.33:8080 Referer: http://192.168.1.33:8080/ sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96" sec-ch-ua-mobile: ?0 sec-ch-ua-platform: "Windows" Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: cross-site User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) … -
Django serverless timeout in Django admin
My project is set up on AWS Lambda, when I try to open my model in the DjangoAdmin interface I get an timeout message.I know that timeouts are given after > 29 seconds of loadtime. but I don't fully understand why my model gives a timeout. I've tried optimizing everything I know/can with my knowledge on the django side so that opening this model on localhost takes around 5.34ms to load. The only thing that I can think of is that my table has too many rows (6.448.277) which will only grow in the future... could that be the problem here and is there any way I can fix this in the django admin? admin code: Queries on localhost: -
Is there a way to filter by an annotation field where the Count is 0?
Here is the example I am referring to: all_hats = Hats.objects.all() issues=[] issues_to_match = [issue.id for issue in issues] matching_issues_count = Count("issues", filter=Q(issues__id__in=issues_to_match)) qs = all_hats.annotate(matching_issues_count=matching_issues_count) qs.filter(matching_issues_count=0) So if in this case issues is an empty list, when you print qs.matching_issues_count you get 0. So when you qs.filter(matching_issues_count=0) you should get that result no? In reality you return an empty queryset. Furthermore, print(qs.filter(matching_issues_count=0).query) returns an EmptyResultSet ValidationError Any information on this or do I have to structure the query another way? Or add a condition for when issues is empty? Thanks. -
How can I query in Django to a table with multiple conditions?
I have a table with fields channel_id, message_id and status. Each row in this table represents a message from a channel. The status can be SENT, DELIVERED or SEEN. When a user sends a message, a row is added to this table with the status SENT. When a user reads that message, another row is added with the status SEEN. So, for one message, I have multiple rows. I want to retrieve the rows from this table which have not the SEEN status, so I am able to know which message is not read. Is there a way of doing that with only one query to the database? -
How to remove members of a Team Django Python
I have teams and I have members (players). The Team owner is inviting a player to his team by email. And player is accepting invitation to join team. After acceptation they become a member of a invitated team. Now what I want to do is to make it possible for player to leave the team and also give possibility for the team owner remove player from their team. Since I am new with Django I can't achieve it yet. I've tried to create delete_member.html and function delete_member in Views first for Team owner to remove Its member but I don't see anything in that page. What Am I doing wrong? Apps: Team app - Views from django.conf import settings from django.contrib import messages from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect, get_object_or_404 from .models import Team, Invitation from .utilities import send_invitation, send_invitation_accepted @login_required def team(request, team_id): team = get_object_or_404(Team, pk=team_id, status=Team.ACTIVE, members__in=[request.user]) invitations = team.invitations.filter(status=Invitation.INVITED) return render(request, 'team/team.html', {'team': team, 'invitations': invitations}) @login_required def activate_team(request, team_id): team = get_object_or_404(Team, pk=team_id, status=Team.ACTIVE, members__in=[request.user]) userprofile = request.user.userprofile userprofile.active_team_id = team.id userprofile.save() messages.info(request, 'The team was activated') return redirect('team:team', team_id=team.id) @login_required def add(request): if request.method == 'POST': title = request.POST.get('title') if title: … -
Not getting refreshed value for Django Serializer
I have 2 models Model A Fields : a_id, a_name, common_name and Model B Fields : b_id, b_name, common_name and my Serializer is like below for Model B class ModelBSerializer: model_a_obj_list = model_a.objects.all().values(a_id a_name common_name) common_name_list = {} for model_a_obj in model_a_obj_list: common_name_list[model_a_obj['common_name']] = { a_name: model_a_obj['a_name'] a_id: model_a_obj['a_id'] } a_model_details = fields.SerializerMethodField(read_only=True) def get_a_model_details(self, instance): return self.common_name_list.get(instance.common_name) class Meta(BaseObjectSerializer.Meta): model = Model_b This Seems to be working fine for API as i am getting modela data in modelb serializer data /api for model b { b_id: bid b_name:bname common_name: cname { a_name: aname_1 a_id: aid_1 } } Problem is when i do an update on MODEL-A. and change value of parameter lets say a_name: aname_1 changed to aname_2 But this change is not reflecting in api when i am running again Can some one help me, What am i doing wrong here ?? -
Can't access object primary key after creation
I did some primary key changes in my Django project which resulted in cleaning the whole database. I tested basically the whole database and it works correctly besides one thing. When creating object and using new primary key shortly after to redirect to its page- I have an error. zam = Zamowienie.objects.create(zam_nr_zam=nr_zam) return redirect('details', zam_id=zam.zam_id) The zam_id field is my new primary key. I tried to call it by simple return redirect('details', zam_id=zam.pk) but the results are the same. Simplified model: class Zamowienie(models.Model): zam_id = models.IntegerField(unique=True, primary_key=True) zam_nr_zam = models.CharField(max_length=25, unique=True) When I try to access url of the object it works correctly (after creation) http://ip/details/1/ Exact error message: Exception Type: NoReverseMatch Exception Value: Reverse for 'details' with keyword arguments '{'zam_id': None}' not found. 1 pattern(s) tried: ['details/(?P<zam_id>[0-9]+)/$'] Any idea what my caused the issue? -
get() returned more than one Modules -- it returned 2! (REST API - Django)
I am stuck in this issue for almost 2 days. Here is the issue. My models are like this: class Modules(models.Model): module_name = models.CharField(max_length=50) module_duration = models.IntegerField() class_room = models.IntegerField() def __str__(self): return self.module_name class Students(models.Model): name = models.CharField(max_length=50) age = models.IntegerField() grade = models.IntegerField() modules = models.ManyToManyField(Modules) def __str__(self): return self.name My views are here: class StudentsViewSet(viewsets.ModelViewSet): serializer_class = StudentsSerializer def get_queryset(self): student = Students.objects.all() return student def create(self,request,*args, **kwargs): data = request.data new_student = Students.objects.create(name=data["name"], age=data['age'], grade=data["grade"]) new_student.save() for module in data["modules"]: module_obj = Modules.objects.get(module_name=module["module_name"]) new_student.modules.add(module_obj) serializer = StudentsSerializer(new_student) return Response(serializer.data) class ModulesViewSet(viewsets.ModelViewSet): serializer_class = ModudesSerializer def get_queryset(self): module = Modules.objects.all() return module ``` When I POST: { "name": "steve", "age": 16, "grade": 10, "modules": [ { "module_name": "math" }, { "module_name": "physics" } ] } It says: MultipleObjectsReturned at /app_Five/student/ get() returned more than one Modules -- it returned 2! I understand get() only get one element. But I think in "for" loop above only one "module_name" exists for each loop. So each time the get() executes, only one result for it to get. Can anyone tell me what I did wrong there? -
obfuscate Django Project
Similar questions has been already asked: How would I package and sell a Django app? But no real answer was provided previously! I have developed a Django app and to satisfy constraint of a security checklist, I have to obfuscate the project, otherwise the project will not get the necessary permits to be used by my client. I don't really care if it's a wast of time or if a determined person is eventually able to break the code. All I'm looking for is a reliable way to obfuscate the project while it's still perfectly functional. I don't mind if it can be deobfuscate after 1 second. -
Django: Unable to implement SimpleJWT
I am working on implementing Simple JWT authentication in Django. I followed the documentation and everything worked fine on my local machine. Now when I was replicating the steps on the server, an error occurred. To give a background, some migration files were deleted earlier, and makemigrations command was giving errors since dependencies were non-existent. Now I went on to this step of rotating refresh tokens, unaware of the fact that some migration files are missing, and ran the migrate command. Now after running the migrate command, Django started throwing errors, but the two token tables (token_blacklist_blacklistedtoken, token_blacklist_outstandingtoken) it creates, were created (obviously with a missing column). Now the TokenObtainPairView API started working, but I thought it can fail since we have a missing table column. So I did the following steps to revert back to the previous version. uninstalled djangorestframework-simplejwt Restored the settings.py Deleted the two token tables from DB using drop table command Now, when I'm following the documentation, I am not able to create the token table again, as the migrate command is telling me there is nothing to migrate. Generally, the applied migrations are registered in django_migrations table, but the token tables migrations were not listed …