Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Bootstrap template form doest not updating the form details in DJango
I am facing this issue. Form save url does'nt working. I tried but i didnot get any solution this. Django form doesn't working properly, may be form not saving or URL problem. Any senior django developer, please guide me. Thanks. Codes: enter image description here Editing ---- enter image description here Edit.html (Template) <div class="container"> <div class="row mt-5"> <div class="col-md-12"> <form action="/edit" method="post"> {% csrf_token %} <div class="mb-3"> <label for="exampleInputEmail1" class="form-label">Note Title</label> <input type="text" value="{{post.notes_titles}}" name="ntitles" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> </div> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">Description</label> <textarea name="nt" value="{{post.notes}}" cols="20" rows="7" class="form-control"></textarea> </div> <div class="mb-3"> <label for="exampleInputEmail1" class="form-label">Note Slug</label> <input type="text" name="nslug" value="{{post.notes_slug}}" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> </div> <button type="submit" class="btn btn-primary mb-4" value="Update">Save</button> </form> </div> </div> Views.py Updated Form def editNote(request, notes_id): if request.method=='POST': ntitles = request.POST.get('notes_titles') nt = request.POST.get('notes') nslug = request.POST.get('notes_slug') post = note(notes_id=notes_id, notes_titles=ntitles, notes=nt, notes_slug=nslug) post.save() return HttpResponseRedirect('/notes') else: return render(request, 'iapp/edit.html') -
Syntax Error : Invalid Return in Suitescript [duplicate]
Trying to implement a very simple script that will automate the process of importing CSV files. When on the validation phase when trying to upload the below to Netsuite I get the error: syntax error: invalid return Any thoughts greatly appreciated. Code below I have adjusted the position of the curly braces to the below but this did not resolve the problem. Sorry if this is novice stuff. /** * @NApiVersion 2.0 * @NScriptType ScheduledScript */ require(['N/task',]) function execute(scriptContext){ var scriptTask = task.create({taskType: task.TaskType.CSV_IMPORT}); scriptTask.mappingId = 212; var f = file.load('SuiteScripts/Purchasing Update 2022.csv'); scriptTask.importFile = f; var csvImportTaskId = scriptTask.submit(); }; return{ execute:execute }; -
Django POST http://127.0.0.1:8000/create_member/ 500 (Internal Server Error)
i try to add usernames to my video chatting app and this error occured. I try to fetch create_member but this error occured. I try to solve many times but failed. Kindly Check it. Uncaught (in promise) SyntaxError: Unexpected token. This error occured in console and i can't get my video and audio tracks. Internal Server Error: /create_member/ Traceback (most recent call last): File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\sqlite3\base.py", line 477, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such column: videoApp_roommember.name The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\hp\Desktop\ChattingApp\VideoChatting\videoApp\views.py", line 76, in createMember member, created = RoomMember.objects.get_or_create( File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 657, in get_or_create return self.get(**kwargs), False File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 492, in get num = len(clone) File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 302, in __len__ self._fetch_all() File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 1507, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 57, in __iter__ results = compiler.execute_sql( File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\compiler.py", line 1361, in … -
Websocket connection fails when deploying Django Channels in render.com
I am deploying a project where I use Django Channels to connect users to a websocket. My deployment is working at the core, however, whenever I try to connect to the websocket from the deployed app, I get this traceback on my logs: Oct 11 10:02:31 AM Traceback (most recent call last): ... Oct 11 10:02:31 AM File "/opt/render/project/src/.venv/lib/python3.7/site-packages/aioredis/stream.py", line 24, in open_connection Oct 11 10:02:31 AM lambda: protocol, host, port, **kwds) Oct 11 10:02:31 AM File "/usr/local/lib/python3.7/asyncio/base_events.py", line 971, in create_connection Oct 11 10:02:31 AM ', '.join(str(exc) for exc in exceptions))) Oct 11 10:02:31 AM OSError: Multiple exceptions: [Errno 111] Connect call failed ('::1', 6379, 0, 0), [Errno 111] Connect call failed ('127.0.0.1', 6379) Oct 11 10:02:32 AM 2022-10-11 15:02:32,909 ERROR Exception inside application: Multiple exceptions: [Errno 111] Connect call failed ('::1', 6379, 0, 0), [Errno 111] Connect call failed ('127.0.0.1', 6379) Oct 11 10:02:32 AM Traceback (most recent call last): Oct 11 10:02:32 AM File "/opt/render/project/src/.venv/lib/python3.7/site-packages/channels/utils.py", line 51, in await_many_dispatch Oct 11 10:02:32 AM await dispatch(result) Oct 11 10:02:32 AM File "/opt/render/project/src/.venv/lib/python3.7/site-packages/channels/consumer.py", line 73, in dispatch Oct 11 10:02:32 AM await handler(message) Oct 11 10:02:32 AM File "./signup/consumers.py", line 41, in websocket_connect Oct 11 10:02:32 AM self.channel_name Oct … -
Getting multiple columns from 4 different tables in Django Rest Framework
I'm really new to ORM and also new to Django. Here's my models. class User(models.Model): id = models.AutoField() email = models.EmailField() class ToDo(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey("User", on_delete=models.CASCADE) title = models.TextField(max_length=50) detail = models.CharField(max_length=250) class ToDoResult(models.Model): id = models.AutoField(primary_key=True) todo = models.ForeignKey("ToDo", on_delete=models.CASCADE) is_done = models.BooleanField(default=False) class ToDoDay(models.Model): DAY_CHOICES = ( ("0", "MON"), ("1", "TUE"), ("2", "WED"), ("3", "THU"), ("4", "FRI"), ("5", "SAT"), ("6", "SUN"), ("7", "ALL") ) id = models.AutoField(primary_key=True) todo = models.ForeignKey("ToDo", on_delete=models.CASCADE) day = models.CharField(max_length=1, choices=Category.choices) And what I want to get would be the same as the result of this sql query. SELECT user.id, todo.title, result.is_done, day.day FROM USER as user LEFT JOIN TODO as todo ON user.id = todo.user_id LEFT JOIN TODORESULT as result ON todo.id = result.todo_id LEFT JOIN DAY as day ON todo.id = day.todo_id WHERE user.id = 1 AND day.day = 1; I already kinda implemented this by really naive approach but my code looks so messy. I tried to make a serializer to get all things at once but I got an error message that says like serializer isn't following DB schema kind of thing. How can I achieve it like every other django gurus do? Everyone else's codes … -
How to setup virtual environment inside github desktop?
We recently started use github-pre-commits for django project since then I am not able to commit changes using github desktop. I have activate my virtual env and use terminal only for commiting changes can i make any changes which would let me commit changes from github desktop -
Django Models: Aggregate Avg def objects
I am looking to calculate an average of the "percent" by "name", the origins of the mother on one side and the father on the other. I made my dictionnary, but maybe I'm using the AVG method wrong. Here is my code, I specify that name and percent are not in the database and cannot be in it. @property def mother_origines(self): if self.mother and self.mother.total_origines != 0: return self.mother.total_origines['name'], self.mother.total_origines['percent'] else: return 0 @property def father_origines(self): if self.father and self.father.total_origines != 0: return self.father.total_origines['name'], self.father.total_origines['percent'] else: return 0 @property def total_origines(self): if self.mother_origines != 0 and self.father_origines != 0: ori = self.mother.total_origines, self.father.total_origines return ori.aggregate(models.Avg('name')) if self.birth: return {'name':self.birth, 'percent':100.00} else: return 0 -
Django - queryset chain condition to many_to_many relation
'''class Category(Model): name = models.CharField(max_length=45) class Animal(Model): name = models.CharField(max_length=45) categories = models.ManyToManyField(Category) @receiver(pre_save, sender=Animal) def animal_create_update(sender, **kwargs): # get the selected categories and do something print(categories)''' -
NetSuite Mass Update script runs sucessfully, but nothing gets updated
Have been a developer for years, but just getting into NetSuite scripting. I wanted to start simple and create a script that would update the COMMENT field for all items on a purchase order. I started off by following the tutorial found here. My modified script is below - it should update the MEMO field at the PO header and then every line's COMMENT field. I followed the steps in the article to save the script, create a Mass Update and then run it. In my criteria I set: "Transaction Number/ID" and "has keyword 90999" (just so it would only run on one specific purchase order). I confirmed my criteria was correct by clicking "Preview" and it only returns that one PO. When I run the Mass Update, it runs fine and says it has been run successfully on 1 record (which is good). The MEMO field at the PO header DOES get updated, but the COMMENT field for each line does not. Am I doing something wrong or missing something simple? Is the getLineCount call not the correct one to use? Note that I was doing all this in our Sandbox environment in case that makes any difference UPDATE: … -
Django Rest Framework filtering results displayed by serializer in a Model.objects.all() query
I am trying to query my entire user database but only add the user to the json response if the field account_type is "supplier", right now it is just adding every user to the json response models.py class UserProfile(models.Model): <omitted> account_type = models.CharField(max_length=200, default=None) ...<omitted> views.py class getusers(viewsets.ModelViewSet): # Database model queryset = UserProfile.objects.all() # Serializer - this performs the actions on the queried database entry serializer_class = GetUsersSerializer serializers.py class GetUsersSerializer(serializers.ModelSerializer): class Meta: model=UserProfile fields=['user','company','email','pk', 'account_type'] current JSON response [ { "user": 1, "company": "kyle att", "email": "<omitted>", "pk": 1, "account_type": "user" }, { "user": 2, "company": "kyle google", "email": "<omitted>", "pk": 2, "account_type": "supplier" } ] desired JSON response [ { "user": 2, "company": "kyle google", "email": "<omitted>", "pk": 2, "account_type": "supplier" } ] -
use validate method to post the data that is assigned to particular user in django rest Framework
I have user registration with user and project as foreign key and using serializer I wanted to choose only that project that is assigned to particular user but I can't figure out how to use validate method class ProjectUserRegistrationSerializer(ModelSerializer): class Meta: model = ProjectUserRegistration fields = ( 'id', 'date', 'start', 'start_note', 'started', 'started_at_location', 'end', 'end_note', 'ended', 'ended_at_location', 'project', ) def create(self, validated_data): user_obj = ProjectUserRegistration.objects.create( **validated_data, user=self.context['request'].user ) return user_obj and that's my viewset class ProjectUserRegistrationViewSet(viewsets.ModelViewSet): authentication_classes = [authentication.TokenAuthentication, authentication.SessionAuthentication] queryset = ProjectUserRegistration.objects.none() serializer_class = ProjectUserRegistrationSerializer def get_serializer_context(self): context = super(ProjectUserRegistrationViewSet, self).get_serializer_context() context.update({ 'request': self.request, }) return context -
setting up headers properly in nginx after a django app
How do I properly set up these headers from a django app on nginx CSRF_TRUSTED_ORIGINS = [] CORS_ALLOW_METHODS = [ "GET", "OPTIONS" ] SECURE_REFERRER_POLICY = "strict-origin-when-cross-origin" X_FRAME_OPTIONS = 'SAMEORIGIN' CORS_REPLACE_HTTPS_REFERRER = True HOST_SCHEME = "https://" SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_SECONDS = True SECURE_FRAME_DENY = True /etc/nginx/sites-available/urban-train What I have so far current nginx file -
Python/Django Rest Framework put same value objects in one list of dictionaries
I want to put the datas to one list of dictionaries if the label value of the objects are the same Just like the example below: dataPoints: [ { x: new Date(2017,0), y: 1000, label:"Austria" }, { x: new Date(2018,0), y: 1111, label:"Austria" }, { x: new Date(2019,0), y: 2000,label:"Austria" }, { x: new Date(2020,0), y: 1224,label:"Austria" }, { x: new Date(2021,0), y: 4294,label:"Austria" }, ] For this i did something like this: class CustomBusinessIntelligenceList(generics.ListAPIView): queryset = BusinessIntelligence.objects.all().order_by("-years__year") serializer_class = BusinessIntelligenceSerializer filter_backends = [DjangoFilterBackend] filterset_class = CustomBusinessInteligenceFilter def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) dummy_response = [] mapping = {} for count in range(0, len(queryset)): dummy_response.extend([{"x": datetime.datetime(queryset[count].years.year, 1, 1), "y": queryset[count].amount, "label": queryset[count].countries.name}]) for d in dummy_response: print(d) return Response(dummy_response) This gave me this response. That i do not want to see: { "x": "2014-01-01T00:00:00", "y": "51717.5", "label": "Austria" }, My best attempt was this and this did not give me the response that i wanted: class CustomBusinessIntelligenceList(generics.ListAPIView): queryset = BusinessIntelligence.objects.all().order_by("-years__year") serializer_class = BusinessIntelligenceSerializer filter_backends = [DjangoFilterBackend] filterset_class = CustomBusinessInteligenceFilter def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) dummy_response = [] mapping = {} for count in range(0, len(queryset)): dummy_response.extend([{"x": datetime.datetime(queryset[count].years.year, 1, 1), "y": queryset[count].amount, "label": queryset[count].countries.name}]) for d … -
Django - user cannot login after password rest via rest api
I've created a custom user model as described in the django documentation https://docs.djangoproject.com/en/4.1/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project : from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): pass Changed the AUTH_USER_MODEL in settings.py: AUTH_USER_MODEL = 'users.CustomUser' and created a serializer using django rest-framework: from rest_framework import serializers from users.models import CustomUser class CustomUserSerializer(serializers.ModelSerializer): def create(self, validated_data): user = super().create(validated_data) # user = CustomUser.objects.create_user(**validated_data) if validated_data.get('password'): password = validated_data.get('password') user.set_password('password') print("set password to ", password) user.save() return user def update(self, instance, validated_data): if validated_data.get('password'): password = validated_data.get('password') instance.set_password('password') instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.email = validated_data.get('email', instance.email) instance.save() return instance class Meta: model = CustomUser exclude = ['last_login', 'is_superuser', 'is_staff', 'is_active', 'date_joined', 'groups', 'user_permissions'] Creating a new user and updating it via rest works fine. But I cannot login with that user and the given password. I've tried it via the api authentication given by the rest framework path('api-auth/', include('rest_framework.urls')), as well as tried to login into the admin backend after giving the user staff status there. The password string displayed in the admin interface for that user seems to be fine: algorithm: pbkdf2_sha256 iterations: 390000 salt: 2DrB5n**************** hash: eflTzs************************************** It seems, that calling set_password on the instance within the serializer methods works. However, no … -
HTML IF function with date.time
In my Django/Python app I have an queryset with 3 conditions: queryset = Post.objects.filter(verifikacija='False', status='Zatvorena', date_zatvoreno__lte=datetime.now(pytz.utc) - timedelta(days=30)) Now, I need to make those same conditions in my HTML IF function. {% if user.is_superuser or user.is_staff %} {% if object.status == 'Zatvorena' and post.verifikacija != 'True' and post.date_zatvoreno__lte == datetime.now(pytz.utc) - timedelta(days=30) %} <a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'post-delete' object.id %}">Delete</a> {% endif %} {% endif %} Problem is, I don't know how to check time or how to calculate time in HTML. Do I need to write a seperate script or? -
How to update user details in custom user model in django
i just created a custom user model from abstractuser. I can create user but update is not working showing some error. I am also week in english so idk how to share my problem. In short hand i want to edit email and password of a user. ###This is my user model class User(AbstractUser): roles =( ('Admin','Admin'), ('Placement Manager','Placement Manager'), ) username=models.CharField(max_length=100,null=True,blank=True) email = models.EmailField(max_length=50, null=True,blank=True) phone = models.IntegerField(unique=True) role = models.CharField(max_length=100,choices = roles,null=True,blank=False) USERNAME_FIELD = 'phone' REQUIRED_FIELDS = ['email','username','role'] objects=UserManager() def get_username(self): return self.email ###This is my view def editPlacementManager(request): if request.method=='POST': name=request.POST.get('name') phone=request.POST.get('phone') email=request.POST.get('email') password=request.POST.get('password') userid = request.POST.get('pmId') User.objects.get(id=userid).update(username=name,phone=phone,email=email,password=password,role='Placement Manager') return redirect('listplacementmanager') return render(request,"index/placementmanager.html") ### The error is AttributeError at /editplacementmanager 'User' object has no attribute 'update' -
Problem django.core.exceptions.ImproperlyConfigured with django.test
I am trying to run a simple django test: tests.py from django.test import TestCase class EasyTest(TestCase): def test_1(self): x = 2 y = x * 2 self.assertEqual(y, 4) settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'db01', 'USER': 'admin', 'PASSWORD': '18101974Oo', 'HOST': 'localhost', 'PORT': 44321, }, } But I am getting an error django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. If i use the same code but do import from unittest everything works -
Is there a way to render a docx file using Django Template?
I'm creating a function that takes two arguments: A list of documents, and a dictionary containing values with key names that matches the keywords in the documents, which are identified by two curly braces around them: {{Value}}. I'm supposed to combine all the documents into a single document and render this document using Django Template. Django would automatically read the keywords and replace them with the dictionary values. Simple as that, right? I suppose not, but i gotta ask. Is there any way of doing this? Is this even possible? Just to clarify, i already combined all documents into one, so it's only rendering it that is confusing me. Has anyone gone through a similar situation? -
Why does my image not show when i upload an image in django but when
Images dont show in the web browser when i try to upload an image But it show me the location of the image and it is valid any help please enter image description here -
Django Rest Framework - display child value on parent serializer without making too many extra queries
I have this two models: class Parent(models.Model): name = models.CharField(max_length=255) level = models.IntegerField() class Child(models.Model): parent = models.ForeignKey(Parent, related_name='children') therefore_name = models.CharField(max_length=255) level = models.IntegerField() active_from = models.DateTimeField(auto_now_add=True) active_to = models.DateTimeField(null=True, blank=True) Child model is used to be able to "overwrite" values on parent, and there is validation to prevent a parent with multiple overlapping children with the same active_from and active_to dates. My view: class FacilityViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = ParentSerializer def get_queryset(self): now = timezone.now() parents = Parent.objects.all().prefetch_related( Prefetch('children', queryset=Child.objects.exclude(valid_from__gt=now, valid_from__isnull=False).exclude(valid_to__lt=now, valid_to__isnull=False).distinct()) ) return parents My serializer: class ParentSerializer(serializers.ModelSerializer): class Meta: model = Parent fields = ['id'] def to_representation(self, instance): representation = super().to_representation(instance) if hasattr(instance, 'children') and instance.children.exists(): child = instance.children.first() else: child = Child(therefore_name=instance.name, level=instance.level) representation['name'] = child.therefore_name representation['level'] = child.level return representation This works, but the code makes alot of extra queries. Is there something I could do to cut the queries down? This is the code that is makes extra queries: if hasattr(instance, 'children') and instance.children.exists(): child = instance.children.first() -
How to load save image to Django models from csv file
I am having trouble saving image in ImageField from CSV file. I can save everything except image and I have no idea what to do. views.py def read_csv_file(request): if request.method == "POST": uploaded_file = request.FILES['csv_file'] fs = FileSystemStorage() filename = fs.save(uploaded_file.name, uploaded_file) file = open('C:/Fiverr projects/GrimBlog-main/media/' + uploaded_file.name) reader = csv.reader(file) for _ in range(1): next(file) for row in reader: title = row[0] author = request.user views = row[2] description = row[3] timestamp = strftime("%Y-%m-%d %H:%M:%S", gmtime()) slug = row[5] short_description = row[6] publish_on = strftime("%Y-%m-%d %H:%M:%S", gmtime()) path = row[8] image = Image.open(path) row_9 = str(row[9]) row_10 = (row[10]) if row_9 == "TRUE": featured = True if row_9 == "FALSE": featured = False if row_10 == "TRUE": case_study = True if row_10 == "FALSE": case_study = False create_blog = Post(title = title, author = author, views = views, description = description, timestamp = timestamp, slug = slug, short_description = short_description , publish_on = publish_on, heading_image = image, featured = featured, case_study = case_study).save() return render(request, 'blog/upload_blogs.html') models.py class Post(models.Model): title = models.CharField(max_length=30) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) views = models.IntegerField(default=0) description = RichTextUploadingField(blank=True, null=True) timestamp = models.DateTimeField(blank=True, auto_now_add=True) slug = models.CharField(max_length=33, unique=True) short_description = models.TextField(max_length=400) publish_on = models.DateTimeField() heading_image = … -
APIView - How to raise a 400 Bad Request and be caught by the exception handler
I am trying to raise a BadRequest error in my APIView and I wish it to be caught by the custom exception handler I have created. My current setup doesn't catch the exception. Could I please have some help as to why this may be happening settings.py REST_FRAMEWORK = { ...... 'EXCEPTION_HANDLER': 'src.exceptions.common_exception_handler', } views.py class LoginView(APIView): serializer_class = LoginSerializer permission_classes = (AllowAny,) def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=False) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) exceptions.py def common_exception_handler(exc: APIException, context: dict) -> Response: response = origin_exception_handler(exc, context) ............. ``` -
How to create a dictionary with two querysets from different models, using a common DateTimeField as the dictionary keys?
I would like to create a dictionary from two models with a field dt in common. This field should be the dictionary keys, and fields value and last the keys's value. What is the most efficient way to do that ? class Balance(models.Model): value = models.FloatField(default=0) dt = models.DateTimeField() class Price(models.Model): last = models.FloatField(default=0) dt = models.DateTimeField() The desired output would be something like this : { "2022-10-11T00:00:00Z": { "value": 151.05, "last": 1, }, "2022-10-10T00:00:00Z": { "value": 151.1, "last": 1.1, }, "2022-10-09T00:00:00Z": { "value": 152, "last": 1.1, }, "2022-10-08T00:00:00Z": { "value": 154, "last": 1.23, } } I could iterate through each dictionaries of the querysets with a nested loop and search the items with a common dt then populate key:value inside a new dictionary, but it's not elegant and I don't believe it's efficient. -
Object level permission at ORM level in Django
I have a Django application (mainly a rest API) with a completely custom User model (not inhered from Django). My authentication is based on JWT tokens. I would like to make sure a user cannot access to data of another user. I have checked the django-guardian and django-rules. It provides stuff to call a has_perm function. However, in the case the developer does not perform the check and makes a mistake (for example hardcoding the user id in a query), a user might be able to access someone else data Is there any way to enforce some kind of rule at the ORM level? -
Django vs Laravel — Which framework to choose? [closed]
Django vs Laravel — Which framework to choose for a level business ERP? who can guide me about this what I can learn for Django what I used for web design of Django so please guide me in right way.