Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to return current user's booking history in django rest framework?
I have created a booking api where user have to login to book a package ( holiday package). Now how can a user after login check their booking history that means the bookings that they made? That means I want to create an api where if a user clicks my bookings, it will return the bookings that the user has made. My booking model: class Booking(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) package = models.ForeignKey(Package, on_delete=models.CASCADE, related_name='package') name = models.CharField(max_length=255) email = models.EmailField() phone = models.CharField(max_length=255) bookedfor = models.DateField() created_at = models.DateTimeField(auto_now_add=True) class Package(models.Model): destination = models.ForeignKey(Destination, on_delete=models.CASCADE) package_name = models.CharField(max_length=255) featured = models.BooleanField(default=False) price = models.IntegerField() duration = models.IntegerField(default=5) discount = models.CharField(max_length=255, default="15% OFF") discounted_price = models.IntegerField(default=230) savings = models.IntegerField(default=230) special_discount = models.BooleanField(default=False) My booking serializer: class BookingSerializer(serializers.ModelSerializer): # blog = serializers.StringRelatedField() class Meta: model = Booking fields = ['name', 'email', 'phone', 'bookedfor'] # fields = '__all__' My booking view: class BookingCreateAPIView(CreateAPIView): permission_classes= [IsAuthenticated] queryset = Booking.objects.all() serializer_class = BookingSerializer def perform_create(self, serializer): # user = self.request.user package = get_object_or_404(Package, pk= self.kwargs['pk']) serializer.save(user=self.request.user,package=package) -
Python sorted function on queryset objects
I am first trying to sort by created_on descending and then using the same product_users queryset and applying sorted function on foreign_key user object where field is name. But not able to sort by name: Here 'user.name' is a fk relation what i have in ProductUser model. product_users = ProductUser.objects.filter(entity=entity).order_by('-created_on') product_users = sorted(product_users, key=attrgetter('user.name')) -
Create Django app with no User model - 3.1.3 wants to migrate auth_user?
I've got a Django application which has been happily humming along now for quite some time (2 years or so). It's on 3.0.10 currently - when I tried to upgrade to 3.1.3, it says there was a migration for the auth application. No worries! Never been an issue before... I ran python manage.py migrate and got the following error: "Cannot find the object "auth_user" because it does not exist or you do not have permissions." Which, I suppose would be true because we do not have a User model at all in this application. There is no auth_user table, that is correct. In other apps we have an AbstractUser that routes to a table named: org_user - but again: this particular app (and project) do not have any User model associated with them Obviously this (apparently, now) leads to some issues. Any thoughts on how to get around this? I thought about removing auth from installed apps and tried that but it led to more issues when trying to runserver. -
How to create some group of user without password in django?
I am developing multivender ecommerce site in django. In which, i dont want to authenticate some group of user i.e. customer with password but want to authenticate venders with password. How can i do that? -
"<field>":["This field is required."] message Django REST framework
so today I have been trying to implement the Django REST framework for the first time to my project, everything has been working fine I can create, update, and delete post using the browser interface that the framework provides, but after integrating the JWT token and trying to create a post using curl I always get the message "":["This field is required."] . I have tried to troubleshoot it in many ways but there is no way to parse the fields that I need to correctly. I even was able to create a Post using curl but I had to modify the fields to be all "nulls". Am I sending a wrong curl request ? curl: (note that if I add -H "Content-Type: application/json" I get this output {"detail":"JSON parse error - Expecting property name enclosed in double quotes: line 1 column 2 (char 1)"} that has been already solved here Json parse error using POST in django rest api by removing the content-type header) curl -X POST -H "Authorization: JWT <token>" -d '{ "title": "Helloooo", "content": "Hi", "schools": null, "course": null, "classes": [ 1 ], "isbn": 12312, "semester": null, "visible": false }' 'http://127.0.0.1:8000/api/posts/create/?type=post' This is the output that I … -
How to save nested JSON from response?
I have a nested JSON with array, process the response, and now I'm trying to save it into the database (postgresql) but I get this error: django.db.utils.ProgrammingError: column "created_date" of relation "feedback_patient" does not exist LINE 1: ..., "first_name", "last_name", "email", "language", "created_d... ^ this is my model.py class Patient(models.Model): coreapi_id = models.CharField(max_length=100) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(max_length=100) language = models.CharField(max_length=20) created_date = models.DateTimeField(default=True) lastmodified_date = models.DateTimeField(default=True) def __str__(self): return self.email and my views.py where I fetch the API def fetchapi_patients(request): url = 'https://dev-api.prime.com/api/v1/plugins/get-patients' headers={"Authorization":"Bearer eyJ0eXAiOiJKV1JIUzI1NiJ9.eyJpYXQiOjE2MDU2MTkwNzUsImlzcyI6Imh0dHA6XC9cLZyIsImZpcnN0X25hbWUiOiJNaXJvc2xhdiIsImxhc3RfbmF"} response = requests.get(url, headers=headers) #Read the JSON patients = response.json() #Create a Django model object for each object in the JSON and store the data in django model (in database)""" for patient in patients['data']['records']: print(patient['Id']) Patient.objects.create(first_name=patient['FirstName'], last_name=patient['LastName'], email=patient['PersonEmail'], language=patient['Language__c'], coreapi_id=patient['Id'], created_date=patient['CreatedDate'], lastmodified_date=patient['LastModifiedDate']) return JsonResponse({'patients': patients}) and this is my json: "data": { "totalSize": 2, "done": true, "records": [ { "attributes": { "type": "Account", "url": "/services/data/v39.0/sobjects/Account/00126000011" }, "Id": "00126000011", "PersonEmail": "test@gmail.com", "FirstName": "Test", "LastName": "Mike", "Language__c": "Deutsch", "CreatedDate": "2020-11-09T14:48:47.000+0000", "LastModifiedDate": "2020-11-17T12:56:50.000+0000" }, Can anyone see what I'm missing? -
DRF django-rest-framework-simplejwt JWTAuthentication not working
Ideally using django-rest-framework-simplejwt and the authentication class JWTAuthentication, the API should give 403 when I pass the token incorrectly. Instead, when I am making my API request it is executing successfully even without the Authentication token. This is a dummy API, my concern is the Authentication should work. My code looks like this: class ViewSet(viewsets.ModelViewSet): queryset = get_user_model().objects.all() serializer_class = SomeSerializer http_method_names = ("post", "patch") authentication_classes = (JWTAuthentication,) When I debug I see that it is executing JWTAuthentication, which in turn returns None. Which is expected since I am not passing the Token in the header. def authenticate(self, request): header = self.get_header(request) if header is None: return None Now I think the View should give Permission Denied, which is not happening. Not able to understand what is missing here. -
Django process\integrate with payment gateway
I am working on Django ecommerce project, at the checkout page "last page". I already have the customer data and order data, and I want to integrate with the payment gateway. As per the payment gateway documentation, I need to:- 1- Execute the payment Send the customer and some order data in Json format to their end point URL as follow baseURL = "https://apitest.gateway.com" token = 'mytokenvalue' #token value to be placed here def execute_payment(): url = baseURL + "/v2/ExecutePayment" payload = "{\"CustomerName\": \"Name\",\"MobileCountryCode\": \"+001\"," \ "\"CustomerMobile\": \"12345678\",\"CustomerEmail\": \"email@gateway.com\",\"InvoiceValue\": 100," \ "\"DisplayCurrencyIso\": \"USD\",\"CallBackUrl\": \"https://google.com\",\"ErrorUrl\": " \ "\"https://google.com\",\"Language\": \"en\",\"CustomerReference\": \"ref 1\",\"CustomerCivilId\": " \ "12345678,\"UserDefinedField\": \"Custom field\",\"ExpireDate\": \"\",\"CustomerAddress\": {\"Block\": " \ "\"\",\"Street\": \"\",\"HouseBuildingNo\": \"\",\"Address\": \"\",\"AddressInstructions\": \"\"}," \ "\"InvoiceItems\": [{\"ItemName\": \"Product 01\",\"Quantity\": 1,\"UnitPrice\": 100}]}" headers = {'Content-Type': "application/json", 'Authorization': "Bearer " + token} response = requests.request("POST", url, data=payload, headers=headers) print("Execute Payment Response:\n" + response.text) 2- The gateway response should be as follow { "IsSuccess": true, "Message": "Invoice Created Successfully!", "ValidationErrors": null, "Data": { "InvoiceId": 12345, "IsDirectPayment": true, "PaymentURL": "https://apitest.gateway.com/v2/DirectPayment/03052193209041/6", "CustomerReference": "ref 1", "UserDefinedField": "Custom field" } } 3- I should route my customer to the PaymentURL received in the GW response My questions are:- 1- How I inject the needed data in the … -
Django check if time is available in slot using models
I have the following model: class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) time = models.DateTimeField() How would I check if a time that I specify is within 1 hour of any of the orders' times by user 1. Example: I specify a time and post it to an endpoint, the endpoint checks if the giver time is within an hour of any of the other orders with User 1. How would I check if the time is within 1 hour of any of teh order models? -
How do we POST data in django rest framework using function based views?
I am new to django rest framework (DRF) and I need to POST some data using function based views (FDV). I successfully used GET method using this way but have no idea how to use POST method to add values to database. # models.py class Item(models.Model): name = models.CharField(max_length=50) quantity = models.IntegerField() price = models.FloatField() # app/urls.py urlpatterns = [ path('', views.get_data_list, name='list'), path('post_val/', views.post_data, name='post_val'), # need to implement ] # app/serializers.py class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ('id', 'name', 'quantity','price') # app/views.py from django.http.response import JsonResponse from rest_framework.parsers import JSONParser from .models import Item from .serializers import ItemSerializer from rest_framework.decorators import api_view @api_view(['GET',]) def get_data_list(request): if request.method == 'GET': items = Item.objects.all() items_serializer = ItemSerializer(items, many=True) return JsonResponse(items_serializer.data, safe=False) @api_view(['POST',]) def post_data(request): #TO DO If I want to add this new data like this one {name:"Television", quantity:15, price:999.99} to Item table using POST method, How do we do it in FDV? -
Django admin groups permissions and access
I'm searching for a way to customize the Django Administration to support permissions and data based on the user group. For example, I've just created the Developers1, Developers2 groups.. now I've also created the Transaction model, with AdminModel to specify how to list data. what im trying to do is i want each group to only access its own Transaction model, and each group can only add, delete, update and view their own Transactions (eg developers1 group cant access developers2 Transactions and vice versa) any thoughts should be appreciated thanks!:) -
How to make vuejs search work in Django app on heroku?
I worked on a Django project where I am using vuejs for search functionality by creating an API. It works fine on my system. but when I deploy it on Heroku it stops working. search shows nothing. I am using https://unpkg.com/vue@next to use vuejs not cli. I don't understand what's wrong. do I need to do anything before deploying? -
Caching for a REST API made with Django Rest Framework
I am building a REST API with Django + Django Rest Framework, and now I am concerned about adding some cache to improve the response time. I've already configured Redis as a cache backend. I have seen that Django has multiple cache mode, like per-site or per-view, where you have to configure a cache time. My main concern is about avoiding stale responses. Let's say I configured a 5min cache when listing some resources. The user navigates to this list, then POSTs a resource and comes back to the list. If the list is cached for 5 minutes the first time, How can I avoid that he gets a cached result without the added resource the second time he displays the view? I was expecting some kind of "automatic smart cache" that would be enabled for GET requests and cleared after receiving a PUT or POST request. But...well, I can't find anything like this. I have seen that it is possible to configure the cache with Django's low level API cache.add and cache.delete. But this does not seem to be a good solution as it would ask a lot of custom code for each view. I would prefer to seperate … -
Razorpay Python Track Failed Transaction or Payments
I am using Razorpay for my websites payment gateway, I am using pythons razorpay library for payment integration, I am able to get the payments that are successfully captured in my Django Admin(I am using Django version 2.2.3), but I am unable to get the payments that are failed, can anyone help me how can I keep a track on my failed payments.. THANK YOU, -
I have error when migrating my db in django-python
i change my database django default to postgresql and when i try to migrating ... django.db.utils.OperationalError: FATAL: password authentication failed for user "hamid" my settings is install psycop2 but i dont understad my mistake becuse i can enter to shell database by this password but when i migrating i have error DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USRE': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'localhost', 'PORT': '5432', } } and my docker-compose.yml version: '3' services: blogpy_postgresql: image: postgres:12 container_name: blogpy_postgresql volumes: - blogpy_postgresql:/var/lib/postgresql/data restart: always env_file:.env ports: - "5432:5432" networks: - blogpy_network volumes: blogpy_postgresql: external: true networks: blogpy_network: external: true and my .env POSTGRES_USER=postgres POSTGRES_PASSWORD=postgres POSTGRES_DB=postgres and my traceback File "/home/hamid/Documents/django/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/home/hamid/Documents/django/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/home/hamid/Documents/django/venv/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/home/hamid/Documents/django/venv/lib/python3.8/site-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: password authentication failed for user "hamid" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "./manage.py", line 21, in <module> main() File "./manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/hamid/Documents/django/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/hamid/Documents/django/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/hamid/Documents/django/venv/lib/python3.8/site-packages/django/core/management/base.py", … -
Android - Access static file on Django server using Glide fails
I have the following Django model : class MyAccount(AbstractBaseUser): ... profile_picture = models.FileField(upload_to='Images/',default='Images/placeholder.jpg') ... When the user creates this account, he gets a default placeholder image. The registration of the user ( creation of the MyAccount instance for a particular user) works as expected. But my Android App can not get the placeholder image when it is requested. On my local Django development server, I get the following error: [17/Nov/2020 12:54:34] "GET /media/Images/placeholder.jpg HTTP/1.1" 404 2569 Not Found: /media/Images/placeholder.jpg Why is this happening? The image placeholder.jpg exists, so how it can be that the file is not found ? In the LogCat output of Android Studio, I get a similar error when I filter for okhttp. You can also see that the registration is done correctly but the file is not found: 2020-11-17 13:54:32.852 5825-5924/com.example.project D/OkHttp: {"response":"successfully authenticated.","id":1,"email":"abdullah@gmail.com","username":"abdullahc","profile_picture":"http://192.***.*.***:8000/media/Images/placeholder.jpg","date_joined":"2020-11-17T12:54:30.702559Z","token":"88b8ea2cf59ba851f7bac1751946213f5ee5afe9"} 2020-11-17 13:54:32.852 5825-5924/com.example.project D/OkHttp: <-- END HTTP (287-byte body) 2020-11-17 13:54:33.854 5825-5825/com.example.project I/Glide: Root cause (1 of 1) java.io.FileNotFoundException: http://192.168.2.104:8000/media/Images/placeholder.jpg at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:251) at com.bumptech.glide.load.data.HttpUrlFetcher.loadDataWithRedirects(HttpUrlFetcher.java:102) at com.bumptech.glide.load.data.HttpUrlFetcher.loadData(HttpUrlFetcher.java:56) at com.bumptech.glide.load.model.MultiModelLoader$MultiFetcher.loadData(MultiModelLoader.java:100) at com.bumptech.glide.load.model.MultiModelLoader$MultiFetcher.startNextOrFail(MultiModelLoader.java:164) at com.bumptech.glide.load.model.MultiModelLoader$MultiFetcher.onLoadFailed(MultiModelLoader.java:154) at com.bumptech.glide.load.data.HttpUrlFetcher.loadData(HttpUrlFetcher.java:62) at com.bumptech.glide.load.model.MultiModelLoader$MultiFetcher.loadData(MultiModelLoader.java:100) at com.bumptech.glide.load.engine.SourceGenerator.startNextLoad(SourceGenerator.java:70) at com.bumptech.glide.load.engine.SourceGenerator.startNext(SourceGenerator.java:63) at com.bumptech.glide.load.engine.DecodeJob.runGenerators(DecodeJob.java:310) at com.bumptech.glide.load.engine.DecodeJob.runWrapped(DecodeJob.java:279) at com.bumptech.glide.load.engine.DecodeJob.run(DecodeJob.java:234) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636) at java.lang.Thread.run(Thread.java:764) at com.bumptech.glide.load.engine.executor.GlideExecutor$DefaultThreadFactory$1.run(GlideExecutor.java:393) -
Django OneToOneField & Foreignkey - How to get value from related model?
I've been banging my head against this for an whole workday now and tried various suggestions from stackoverflow and other google results, and consulted the django documentation but all to no avail. In my django project I have the two models listed below. The related values in the models are the rowid which is unique to each "Sag". My goal is that when I query using "Sag.objects.all()" that it would also return the group attached to that specific rowid. Ideally it should be a "OneToOneField" and not a "ForeignKey" since the rowid should only exists once in both tables but my latest try had me change it to a "ForeignKey". I have, however, been unable to get the related field with the different solutions I've tried so far class Sag(models.Model): id = models.IntegerField(blank=True, null=False, primary_key=True) rowid = models.IntegerField(db_column='RowId', blank=True, null=True) posts = models.TextField(db_column='POSTS', blank=True, null=True) date = models.TextField(db_column='Date', blank=True, null=True) art = models.IntegerField(db_column='Art', blank=True, null=True) class Grouping(models.Model): rowid = models.ForeignKey(Sag, on_delete=models.CASCADE, db_column='RowId') group = models.IntegerField(db_column='Group', blank=True, null=True) Any ideas/ressources as to how i would solve this problem? -
filter a query set based on start_time and duration fields
I want to filter a queryset based on a start time and an end time . The table has the fields , "start_time" and "duration" . start_time is a DateTimeField and duration is an IntegerField which holds the duration in minutes. I want to get a queryset between two times. query_filter = Q() if self.start_time is not None: query_filter.add(Q(virtualclassroommodule__end_time__gt=self.start_time), Q.AND) if self.end_time is not None: query_filter.add(Q(virtualclassroommodule__start_time__lt=self.end_time), Q.AND) self.start_time and self.end_time are the time frames i want to filter with .The above is an example of another working filter. In this example, the model has an end_time field, so it can be done. However i want to accomplish the same when I have only a duration field and a start_time. -
Database error while authenticating user from mongodb connected with django app deployed in gcp
I have deployed django app in Google cloud Platform,I am using mongodb atlas to store users data .I can successfully register and login by running it on localhost.But when i try to register/login directly from the app url ,it's giving database error.In settings.py file ,i have given connection string of mongodb database.How would i be able to access data stored in mongodb through app deployed in gcp ? The resources which are used are App Engine alongwith cloud sdk to deploy. The Database connection in settings.py file is as follow: DATABASES = { 'default': { 'ENGINE': 'djongo', 'CLIENT': { 'name' : 'Haley', 'host':'mongodb+srv://username:password@haley.tdyg9.mongodb.net/Haley?retryWrites=true&w=majority', 'username': 'username', 'password': 'password', 'authMechanism': 'SCRAM-SHA-1', }, } } The error is as following : DatabaseError at /login No exception message supplied Request Method: POST Request URL: https://haley-295802.ew.r.appspot.com/login Django Version: 3.0.5 Exception Type: DatabaseError Exception Location: /env/lib/python3.7/site-packages/djongo/cursor.py in execute, line 59 Python Executable: /env/bin/python3.7 Python Version: 3.7.9 Python Path: ['/srv', '/env/bin', '/opt/python3.7/lib/python37.zip', '/opt/python3.7/lib/python3.7', '/opt/python3.7/lib/python3.7/lib-dynload', '/env/lib/python3.7/site-packages'] Server time: Tue, 17 Nov 2020 12:48:36 +0000 The above exception ( Keyword: None Sub SQL: None FAILED SQL: ('INSERT INTO "django_session" ("session_key", "session_data", "expire_date") VALUES (%(0)s, %(1)s, %(2)s)',) Params: (('gvtlvlakx6bvztpv816net7zp6e86ot7', 'MGEwYWY5ZTEwOWNjZjliZGZjMWQwMTdjMTlkMDQ4YTA1ZDUxNDUwMjp7InVzZXJfaWQiOiJrYXRpZS5wYXRlbEBnbWFpbC5jb20ifQ==', datetime.datetime(2020, 12, 1, 12, 48, 35, 677384)),) Version: 1.3.3) was … -
Django Model not being updated after calling save() method
Im Using django signals to update a foreign key object of a model . @receiver(sender=PointItem, signal=post_save) def PointItemSaved(instance, sender, **kwargs): try: print(f"before save {user.points}") user = User.objects.get(id=instance.user.id) user.points += 100 user.save() print(f"after save {user.points}") except Exception as e: print(f"there is a problem {e}") according to logs , everything is correct . before & after values are correct . but when i check it on admin page it does not changed ! -
During handling of the above exception (badly formed hexadecimal UUID string), another exception occurred:
I have a checkbox list - user check which items to update - <th scope="row"><input type="checkbox" name="document_detail" value="{{ result.id }}" id="result_check"/>{{ result.id }} This is handled in view by: document_request = request.POST['document_detail'] logging.info(document_request) approval_items = [] for document in document_request: logging.info(document) logging.info gives the correct UUID field e.g. 91da274b-208f-4d65-9e5f-d5cbf2860961 after the loop is initiated the value change to simply "9" or the first character of the UUID. e.g. logging.info give "9" hence the correct error of badly formed UUID Is there a correct method of handling this type of item that I'm missing? -
How to write thread modeling in Django?
I am new to the security side, I know my question might be silly but totally new to Thread Modeling. I have a simple Django application and I need to write thread modeling for this application. If any can help me with a simple Thread Modeling Document it will be great help. Thanks & Regards, Mohamed Naveen -
Change URL when link is clicked in iFrame, when the links in question would be created by user input?
From what I can understand, the URLs of site do not change during navigation if the element with the href/src is within an iframe. And there is a way to override this by getting the ID of every single link element that would exist in the iframe and then set the src manually on each, such as in the response to this question Change URL in an iframe using javascript However the links I want to reflect in the URL are to pages created and added to the site by users, and I cannot know in advance what these URLs will be called, so cannot manually link to them in advance. Is there a workaround for this? And if so, is it really worth the effort and possible messiness? The iframe in question is part of a 3rd party library that I have no control over (django-fobi) -
How do you serialize a queryset that has been created by innerjoining different models?
So, I'm trying to serialize a queryset in my ModelsViewSet. This is my code in my viewset. `class StudentReportViewSet(viewsets.ModelViewSet): permission_classes = [ permissions.AllowAny ] serializer_class = GeneralSerializer def get_queryset(self): if self.request.method == 'GET': queryset = StudentReport.objects.all() teststate_name = self.request.GET.get('testid',None) rawmodalstate_name = (self.request.GET.get('byRaw',None)) percmodaltstate_name = (self.request.GET.get('byPerc',None)) stanmodalstate_name = (self.request.GET.get('byStan',None)) convmodalstate_name = (self.request.GET.get('byConv',None)) print('@@@@@@@@@@@@@@@@') if teststate_name is not None: teststate_name= teststate_name.split(',') teststate_name = list(map(int,teststate_name)) print(teststate_name) print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@') queryset= queryset.select_related('test').filter(test_id__in = teststate_name).values('test__subject','student__name','resultsmarked__totalrawscore') queryset= json.dumps(list(queryset), ensure_ascii=False) print('33333333333') print(queryset) return queryset` This is my serializers.py: class StudentReportSerializer(serializers.ModelSerializer): class Meta: model = StudentReport fields= '__all__' These are my models used in my query set: 1)StudentReport class StudentReport(models.Model): idstudent_report = models.AutoField(primary_key=True) student = models.ForeignKey('Students', models.DO_NOTHING, db_column='Student_ID', blank=True, null=True) # Field name made lowercase. test = models.ForeignKey('Test', models.DO_NOTHING, db_column='Test_ID', blank=True, null=True) # Field name made lowercase. resultsmarked = models.ForeignKey(ResultsMarked, models.DO_NOTHING, db_column='ResultsMarked_ID', blank=True, null=True) # Field name made lowercase. standardisedscoretable = models.ForeignKey(Standardizedscoretable, models.DO_NOTHING, db_column='StandardisedScoreTable_ID', blank=True, null=True) # Field name made lowercase. gradetableinternal = models.ForeignKey(Gradetableinternal, models.DO_NOTHING, db_column='GradeTableInternal_ID', blank=True, null=True) # Field name made lowercase. gradetableexternal = models.ForeignKey(Gradetableexternal, models.DO_NOTHING, db_column='GradeTableExternal_ID', blank=True, null=True) # Field name made lowercase. percentiletableid = models.ForeignKey(Percentiletable, models.DO_NOTHING, db_column='PercentileTableID', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'student_report' Test Model class Test(models.Model): idtest … -
Can't change interpreter path in VS Code (working on a Django project, python3)
On the first attempt I was able to change the interpreter, but when I come back to project the path is within suggestions but when I click nothing changes.