Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why am I getting a 415 {detail: 'Unsupported media type "applicaton/json" in request.'} error
I am making a post request to my Django rest framework backend but I keep getting a 415 error when I make the fetch request from React. The request works perfectly when I make it from Django Rest Framework but I get 415 error when I make the POST request from React views.py @api_view(["POST"]) def PaymentCreateView(request): if request.method == "POST": serializer = PaymentSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) React const Support = async () => { const response = await fetch('http://127.0.0.1:8000/support/payment-create/',{ method: "POST", credentials: "include", headers: { "Accept": "application/json", "Content-Type": "applicaton/json", }, body:JSON.stringify({ "user": user, "email": email, "phone_number": phone_number, "number_of_apples": number_of_apples, "amount": amount, "message": message, }) }) let data = await response.json() console.log(data) } useEffect(() => { userpage() }, []) const handleSubmit = (e) => { Support() e.preventDefault() } error [error][1] [1]: https://i.stack.imgur.com/PUWI4.png -
Django - model class with non-persistent attribute that should be refreshed on each call
My User class looks like : class User(AbstractBaseUser, SafeDeleteModel, PermissionsMixin): UNKNOWN = 'Unknown' id = models.AutoField(primary_key=True) email = models.EmailField(unique=True) default_organization = models.ForeignKey(to='Organization', on_delete=models.SET_NULL, null=True, related_name='default_organization', blank=True) organizations = models.ManyToManyField(to='Organization', through='UserOrganizationMembership', related_name='users', blank=True) So a user can be a part of multiple organisations. However, each time he logs in, he must log in through ONE organisation. Now I have two kinds of orgs present - internal, client I have some telemetry setup for my application and the idea is that i want to not send any telemetry for internal orgs. I want to create an attribute in the /users api that returns this flag (flag depends on both the user and the account he logs in through). My view class looks like this: class UsersViewSet(UpdateModelMixin, ListModelMixin, GenericViewSet): queryset = User.objects.all() serializer_class = UserDetailSerializer def get_serializer_context(self): context = super().get_serializer_context() #self.request.user.is_telemetry_enabled =should_send_event(self.request.user, self.request.tenant.is_internal) context.update({"request": self.request}) return context def get_permissions(self): permission_classes = [IsStaff] if self.action in ('list',) else [CanEditUser] return [permission() for permission in permission_classes] What I've looked at : adding a field in model class and setting it in the get_serializer_context. Doesn't work because adding a field in model makes it a class variable, not per instance. second, it still didn't show up … -
How to change default USER Authorisation to custom model in DRF
I have model.py file which has one model named as Tutor class Tutor(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.CharField(max_length=255) password = models.CharField(max_length=255) I want to implement token authentication using this Tutor model, for login and signup. As of now I have setup token authentication and its working good, but its default authorisation is for USER, which get generated using python manage.py createsuperuser, and I want to use Tutor for Authroization. How to go building this, any resources for my usecase would mean a lot :) -
I wants to show image on homepage after login in django
In views.py file in the function what i have to write in code. Model name where the filename is stored is student and field name is filename def home(request): id = request.user.id result = User.objects.get(pk=id) context = {'result' : result} return render(request, 'customer/shome.html', context) -
Django Async View - Model __str__
I'm trying to convert my existing Django 4.1 app to async due to performance reasons. It's more of a struggle than I initially anticipated. Below is some test code: async def diagrams(request): tests = await sync_to_async(list)(Test.objects.filter(name='Test 1')) print(tests) return render(request, 'analyticsApp/test.html') class Test2(models.Model): name = models.CharField(max_length=50, default='', blank=True) def __str__(self): return self.name class Test(models.Model): name = models.CharField(max_length=50, default='', blank=True) testForeignKey = models.ForeignKey(Test2, editable=True, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.name + '_' + self.testForeignKey.name So I kind of figured out how to "filter" objects using async_to_async. However, a problem that I'm struggling to solve is using __str__ in a Model. All of my models use __str__ to give accurate string depcitions of the model. It seems like this cannot be done ? I tried to convert def __str__ to async def __str__ but django is not awaiting this when it is being called so it causes problems. Any idea how to handle this ? -
Why I'm getting "Not Found: /api/products/undefined" instead of /api/products/1?
I want to get data of a single product from "api/products/id" (I'm using Django Rest Framework) and put them into redux store, so when I refresh product's page the data will be actually displayed. The problem is, when I go to "localhost:3000/products/1" (I'm using also React) instead of getting product with id = 1, I get undefined product and no data at all. The deeper point I've found where id is undefined is in views.py Why this problem occurs? It has some connection with migration? I deleted database *.pyc + *.py files except init and then once again run makemigrations and migrate but nothing changed. And how can I solve it? Browser's consol: VS Code terminal views.py @api_view(['GET']) def getProduct(request, pk): print("\n\n\nPlural key: ", pk) # The pk is undefined product = Product.objects.get(id=pk) # So the product also is undefined serializer = ProductSerializer(product, many=False) return Response(serializer.data) serializer.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' models.py from django.contrib.auth.models import User class Product(models.Model): # ID is generating automatically user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200, null=True, blank=True) image = models.ImageField(null=True, blank=True, default='/placeholder.png') brand = models.CharField(max_length=200, null=True, blank=True) category = models.CharField(max_length=200, null=True, blank=True) description = models.TextField(null=True, blank=True) rating = … -
Get first Item in a django orm query for each unique value of a column
I have a table of Snapshots. It has the following attributes: device_ip created_at name There are multiple records in the table. Various records can have the same device_ip but will have unique names. I want to fetch the latest record for each device_ip ordered by created_at. I am using MySQL database. Here is what I tried: Snapshot.objects.filter(device_ip__in=device_ip_list) .order_by("-created_at") .values( "device_ip", "name", "created_at" ).first() But It provides the last record of the table. Suggestions? -
Pycharm Django cannot close development runserver with ctrl + c or ctrl + break
For some reasons I cannot use ctrl + c or ctrl + break (my laptop doesn't have break) to close the django development server in pycharm? But I can use ctrl + c when I want to exit out of terminal from python? So it seems to me that this problem is django specific perhaps? -
Sum based in a condition and group by month - Django query
class Movimentacao(models.Model): entrada_saida = models.CharField(max_length=100) date = models.DateField() movimentacao = models.CharField(max_length=200) produto = models.CharField(max_length=300) instituicao = models.CharField(max_length=200) quantidade = models.IntegerField() preco_unitario = models.DecimalField(max_digits=19, decimal_places=2) valor_da_operacao = models.DecimalField(max_digits=19, decimal_places=2) My goal is to sum valor_da_operacao for each month in date. Besides that, the produto field must be equal to "dividendo" (condition). How can I manage in only one Django query? My expectation is to have a dict like this: {"dict": [["2022-Jan", 1.530], ["2022-Feb", 422], ["2022-Mar", 1.822]]} Thanks! -
Most efficient way to paint columns in django template / view
I have an app where I allow the users to create a customized dashboard containing 'widgets'. They can choose 1,2 or 3 columns and then select widget column and widget order. The widgets will be of differing heights so have to paint in columns rather than rows. I loop through the widgets and annotate with a colno and then send this to the template. during initial dev I've just looped through them all in the template and am now looking to make this a little more efficient. I would expect between 15-20 widgets per page. in the template at the moment I have: <div class="column"> {% for widget in widgets %} {% if widget.colno == 1 %} {% include 'widget.html' %} {% endif %} {% endfor %} </div> <div class="column"> {% for widget in widgets %} {% if widget.colno == 2 %} {% include 'widget.html' %} {% endif %} {% endfor %} </div> <div class="column"> etc </div> Obviously not the most efficient way to do this. Wondering if there are better ways that this could be done: a) Iterate through in the view and assign widgets to dictionaries based on their colno. Then iterate through these in the template. - … -
Can a localhost address be allowed to load a site in an iframe from the csp header?
I would like to know if it is possible to allow localhost to make changes to a specific site by setting it in the csp header in the settings.py file of the Django project. For my part, I am trying to load my Django site in an iframe present on a page at the following address http://localhost:3000/searchEngine. So I inserted this in my settings.py file: CSP_FRAME_ANCESTORS = ("'self'", 'localhost:*') This is taken into account, but still does not allow localhost to load the site in the iframe and I get the following error, when I try to load this site in the iframe: Refused to frame 'https://gkwhelps.herokuapp.com/' because an ancestor violates the following Content Security Policy directive: "frame-ancestors 'self' localhost:*". I don't know not why yet I did not make syntax errors. So I wonder if django-csp takes localhost into account. I would like to allow my site to load in an iframe from any port in my localhost. -
How to check how much session expiry time is left? (Django)
With "views.py" as shown below, I'm trying to check how much session expiry time is left by setting "60" seconds expiry time but after "20" seconds sleep, get_expiry_age(), get_session_cookie_age() and get_expiry_date() didn't return "40" seconds expiry time which is expected: # "views.py" from django.shortcuts import render import time def test(request): request.session.set_expiry(60) # "60" seconds expiry time is set time.sleep(20) # Sleep for "20" seconds print(request.session.get_expiry_age()) # 60 print(request.session.get_session_cookie_age()) # 1209600 print(request.session.get_expiry_date()) # 2022-08-07 00:34:41.700828+00:00 return render(request, 'test/index.html') So, are there any ways to check how much session expiry time is left? -
Dockerizing Django - Unable to visit running localhost
Dockerfile: FROM python:3.9-alpine WORKDIR /app ENV PYTHONUNBUFFERED=1 COPY /drf/ . RUN pip install -r requirements.txt CMD ["python", "manage.py", "runserver"] When I build an image from this Dockerfile and try to run it, it seems to be running successfully (after running docker run <image> I get these logs): Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). August 07, 2022 - 00:42:33 Django version 4.1, using settings 'drf.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. The problem is when I try to visit http://127.0.0.1:8000/ it cannot be reached (This site can’t be reached). What might be the issue? I guess I have to play with ports in my Dockerfile. Thanks in advance! -
many to many relation in a dynamic url
i have this model shema: class A(Models.model): related = models.ManyToManyField("self", null=True) and if i retrieve data from the database like this: >>> result = A.objects.filter(pk=1) >>> result.values('related__id') [{'id': 2}, {'id': 3}] >>> result.values_list('related__id') [(2,), (3,)] >>> result.values_list('related__id', flat=True) [2, 3] how do i put the 2 and 3 in mine url, so for eaxpmle, i have this url: path('relationships/<related_id>/<related_id>/<related_id>', views.relationships.edit), so when i press a button it will give me this url: 'relationships/1/2/3' and when i press again it will given me this url 'relationships/2/3/4' ```somone has an idea? -
How to execute Django dispatched signal in view function?
Info: I want to make app like upload file before submit the form. TusUpload will receive the file data and send signal. if user add multiple files it will send signal multiple time. I want to execute this signal in create_page the Example code is in the below. The create_page function take the files which files signals send by TusUpload and saved into the Attach model object post object also linked. The create_page is just a logic which i want to perform. I hope you will be able to provide the information. views.py class TusUpload(View): def patch(self, request, resource_id, *args, **kwargs): tus_file = TusFile.get_tusfile_or_404(str(resource_id)) chunk = TusChunk(request) if tus_file.is_complete(): # file transfer complete, rename from resource id to actual filename self.send_signal(tus_file) return TusResponse(status=204, extra_headers={'Upload-Offset': tus_file.offset}) def send_signal(self, tus_file): tus_upload_finished_signal.send( sender=self.__class__, metadata=tus_file.metadata, file_id=tus_file.resource_id, filename=tus_file.filename, upload_file_path=tus_file.get_path(), file_size=tus_file.file_size, upload_url=settings.TUS_UPLOAD_URL, destination_folder=settings.TUS_DESTINATION_DIR) signals.py tus_upload_finished_signal = django.dispatch.Signal( providing_args=[ "metadata", "file_id", "filename", "upload_file_path", "file_size", "upload_url", "destination_folder" ] ) views.py def create_page(request): files = [] @receiver(tus_upload_finished_signal) def create_file(sender, **kwargs): filename = kwargs['filename'] files.append(filename) if request.method == 'POST': form = PostForm(request.POST or None, request.FILES) if form.is_valid(): form.save(commit=False) form.instance.author = request.user form.save() for f in files: attach = Attach() attach.file = f attach.post=form.instance attach.save() return redirect('index_page') else: form = PostForm() … -
Django and Golang hosting
I'm just here to ask a few questions. I am not asking for hosting provider advice or anything of the sort. Some information; I have 2 servers, and no load balancer. I host my Django instance on server 1 I host my staticfiles and media on server 2, using a golang webserver. Server 2 hosts files trailing with /static/ and /media/ (Django does not use these URLS) What I want to do however, is run the two instances, basically side by side using the same URL. So the URLs would kind of look like this (example): ('/', django) ('/*', django) ('/static/*', GOLANG static server) ('/media/*', GOLANG static server) CDN's are not an option, unfortunately. Redirects are not an option. I need to host everything from a single instance. This means one ip address, one protocol, one server. -> Instead of django serving all staticfiles, django neglects the request, and just gives up hosting -> Golang server takes over, serves staticfiles, returns control. I have two servers (machines) to my disposal, but if using just one of the two takes away a lot of complexity, it is acceptable. I do not need to use both machines. So if it is possible … -
Django display Date in input box
I have an program that allows to save information about an expense. I currently trying to implement a settings option to set a range of dates. At this very moment, Django and Jinja by default, show the date format as m/d/y but I would like it to be d/m/y. The form properly displays the date that is already saved to the page from the database. forms.py class SettingsForm(forms.ModelForm): start_date = forms.DateField( label='', widget=DateInput( attrs={ 'class': 'form-control', 'style': 'width: 200px;', }, ), initial=date(date.today().year, date.today().month, 1) ) end_date = forms.DateField( label='', widget=DateInput( attrs={ 'class': 'form-control', 'style': 'width: 200px;', }, ), initial=date(date.today().year, date.today().month, 28) ) class Meta: model = Settings fields = [ 'start_date', 'end_date' ] widgets = { 'start_date': DateInput(), 'end_date': DateInput(), } And it displays like this: Saved date wrong format If I add the format in the widget. widget=DateInput( attrs={ 'class': 'form-control', 'style': 'width: 200px;', }, format='%d/%m/%Y' ) Ends up like this: No date, format was not applied Erases the value stored in the database and does not do the job because format it's still m/d/y. How can I keep the date from the database and format it to d/m/y? -
how does unit testing works in django? (with coverage)
i am finding it kinda confusing to do unit testing especially with fields that has blank=True attribute or unique=True look at this for example: class TagTest(TestCase): def create(self): tag = models.Tag.objects.create(name='test') return tag def test_get(self): tag = self.create() self.assertIsInstance(tag, models.Tag) self.assertEqual(tag.name, tag.__str__()) self.assertEqual(len(tag.name),4)class TagTest(TestCase): def create(self): tag = models.Tag.objects.create(name='test') return tag def test_get(self): tag = self.create() self.assertIsInstance(tag, models.Tag) self.assertEqual(tag.name, tag.__str__()) self.assertEqual(len(tag.name),4) look at coverage for example, it is telling me i am not covering the test case at all -
How any web hosting site protect files from deleting?
I am creating a python code testing (pytest) website using django and deploy on azure and I just test a code and try to delete files in the root directory of my project using shutil.rmtree() but It returns code like this ============================= test session starts ============================== platform linux -- Python 3.9.7, pytest-7.1.2, pluggy-1.0.0 rootdir: /tmp/8da77f5e80b846d collected 1 item codes/test_with_pytest.py F [100%] =================================== FAILURES =================================== _______________________________ test_check_test ________________________________ def test_check_test(): from .code import check_test > assert check_test() == 90 /tmp/8da77f5e80b846d/codes/test_with_pytest.py:3: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /tmp/8da77f5e80b846d/codes/code.py:7: in check_test shutil.rmtree('/') /opt/python/3.9.7/lib/python3.9/shutil.py:726: in rmtree _rmtree_safe_fd(fd, path, onerror) /opt/python/3.9.7/lib/python3.9/shutil.py:663: in _rmtree_safe_fd _rmtree_safe_fd(dirfd, fullname, onerror) /opt/python/3.9.7/lib/python3.9/shutil.py:663: in _rmtree_safe_fd _rmtree_safe_fd(dirfd, fullname, onerror) /opt/python/3.9.7/lib/python3.9/shutil.py:663: in _rmtree_safe_fd _rmtree_safe_fd(dirfd, fullname, onerror) /opt/python/3.9.7/lib/python3.9/shutil.py:663: in _rmtree_safe_fd _rmtree_safe_fd(dirfd, fullname, onerror) /opt/python/3.9.7/lib/python3.9/shutil.py:683: in _rmtree_safe_fd onerror(os.unlink, fullname, sys.exc_info()) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ topfd … -
Django Admin: How to merge items with same name to simplify view
Big Django newbie here. I have an admin view grouping items like this, tho as the number of bids grows it would be tiresome for one to scroll down all the items, so I wanted to group them by the item names that once clicked would show the columns 'bidder' and 'value'. The Admin page: https://i.imgur.com/VOjrlQZ.png I was looking into aggregate and annotate to merge them. Am I looking for the right thing? The model in question is this: class Bid(models.Model): item = models.ForeignKey(Auction_Listing, on_delete=models.CASCADE, related_name='items', related_query_name='item') bidder = models.ForeignKey(User, on_delete=models.CASCADE, related_name='bidders', related_query_name='bidder') value = models.DecimalField(max_digits=10, decimal_places=2, default=0) def __str__(self): return f"{self.item}" In the Admin I got: class BidAdmin(admin.ModelAdmin): list_display = ('item', 'bidder', 'value') def get_queryset(self, request): queryset = super(BidAdmin, self).get_queryset(request).order_by('item') return queryset Any help appreciated! -
How to use return redirect as a callback function in Django
I have been trying to get my code working through out the whole day. I have a view function but its too verbose plus i am trying to use its implementation on another view so i am trying to refactor the code for the function to be able to run in another view. Have been able to get the function to work except for the fact that there is a return redirect with the profile name within the function(its just a plain function and not a view function). Everytime i try to run the code by passing the redirect as a call back function it always produces an HttpRedirectError and also displays the location of the object in memory, how can i go about using the return redirect as a callback or whichever way i can get it working with my code. The Function code: def foo(filter,images,request,redirector): #do something return redirect(redirector) The View Code: if something: foo(filter,images,request,'home') For the View have also tried: def redirector(): return 'home' foo(property,images,request,redirector) Is there any way i can get this to work, if i don't get it to work, would have to repeat unecessary codes for another function. -
Cant make Django execute only one query with multiple joins using .all()... or even .raw(sql) methods
I'm new to Django and wanted to give it a try to convert an already existing PHP application to Django. But I'm already stuck creating a queryset over multiple joined tables so only one sql query would be executed. I'm using a MySql DB. I already managed to create a view that reduces the amount of queries with .all(), .filter, .order_by and multiple .select_related but couldn't get it to make only one sql query call. So I thought I should maybe use the .raw(sql) method, but even using this approach made Django execute hundrets of single sql queries not respecting the joins. Maybe you could help me a bit getting this, normally simple thing, to work in Django? Here's my original SQL query which works absolutely fine if run in MySql and gives a nice resultset: SELECT `hosts`.`id`, `hosts`.`hostname`, `domains`.`domain_name`, `hosts`.`description`, `hosts`.`installation_by_company_id`, `hosts`.`care_by_company_id`, `hosts`.`system_care_by_department_id`, `hosts`.`system_care_accounting_type_id`, `os`.`operatingsystem`, `os`.`lsbdistcodename`, `os`.`lsbdistrelease`, `os`.`lsbmajdistrelease`, `system_care_department`.`department_name` AS `system_care_department`, `additional_software_care_department`.`department_name` AS `additional_software_care_department`, `system_installation_company`.`company_name` AS `system_installation_company`, `system_installation_company`.`company_abrebreation` AS `system_installation_company_abrebreation` FROM `hosts` JOIN `domains` ON `hosts`.`domain_id` = `domains`.`id` JOIN `hosts_fix_data_scans` ON `hosts_fix_data_scans`.`host_id` = `hosts`.`id` JOIN `os` ON `os`.`id` = `hosts_fix_data_scans`.`os_id` JOIN `companies_departments` ON `companies_departments`.`id` = `hosts`.`system_care_by_department_id` JOIN `companies_departments` AS `system_care_department` ON `system_care_department`.`id` = `hosts`.`system_care_by_department_id` JOIN `companies_departments` AS `additional_software_care_department` ON … -
Django served with apache: how to set PYTHONPATH?
I have a Django app that works fine when served with the command "python manage.py runserver". Now I want to have the app served by Apache and got some issues. One issue is that somehow I can't not set PYTHONPATH. I tried either of the following two ways to set it in a apache conf file: WSGIPythonHome /data/anaconda3/envs/partsdb WSGIPythonPath /data/partsdb/partsdb or WSGIDaemonProcess partsdb python-home=/data/anaconda3/envs/partsdb python-path=/data/partsdb/partsdb But I got errors saying PYTHONPATH = (not set). Below is the whole error message from the apache server. Current thread 0x00007fb4880ad940 (most recent call first): <no Python frame> Python path configuration: PYTHONHOME = '/data/anaconda3/envs/partsdb' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/data/anaconda3/envs/partsdb' sys.base_exec_prefix = '/data/anaconda3/envs/partsdb' sys.platlibdir = 'lib64' sys.executable = '/usr/bin/python3' sys.prefix = '/data/anaconda3/envs/partsdb' sys.exec_prefix = '/data/anaconda3/envs/partsdb' sys.path = [ '/data/anaconda3/envs/partsdb/lib64/python38.zip', '/data/anaconda3/envs/partsdb/lib64/python3.8', '/data/anaconda3/envs/partsdb/lib64/python3.8/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' When I ran python (both /usr/bin/python3 and /data/anaconda3/envs/partsdb/bin/python3) from the commandline, I didn't get errors from the code import encodings. The apache server kept running and … -
Why is the code creating an empty object in Django Rest Framework
For some reason, when I send my data from my frontend, the backend will create an empty objects. models.py class Workout(models.Model): GOALS_CHOICES = ( ('None', 'None'), ('Abs', 'Abs'), ('Arms', 'Arms'), ('Cardio', 'Cardio'), ('Core', 'Core'), ('Endurance', 'Endurance'), ('Flexibility', 'Flexibility'), ('Full Body', 'Full Body'), ('Legs', 'Legs'), ('Lower Body', 'Lower Body'), ('Power', 'Power'), ('Shoulders', 'Shoulders'), ('Sport Conditioning', 'Sport Conditioning'), ('Stability', 'Stability'), ('Strength', 'Strength'), ('Toning', 'Toning'), ('Upper Body', 'Upper Body'), ('Weight Loss', 'Weight Loss') ) exercises = models.ManyToManyField(Exercise, through='Targets') name = models.CharField(max_length=200, blank=True) profile = models.ForeignKey(Profile, on_delete=SET_NULL,null=True, blank=True) description = models.TextField(max_length=3000, blank=True) goals = models.CharField(max_length=25, choices=GOALS_CHOICES, default='None') workout_time = models.CharField(max_length=200, blank=True) difficulty = models.CharField(max_length=10,blank=True) status = models.CharField(max_length=15, default='Created') created = models.DateField(auto_now_add=timezone.now()) assigned = models.DateField(blank=True, null=True) completed = models.DateField(blank=True, null=True) time = models.CharField(max_length=100, blank=True, null=True) rating = models.IntegerField(default=0, blank=True, null=True, validators=[MaxValueValidator(5), MinValueValidator(0)]) overall_notes = models.TextField(max_length=3000, blank=True) favorited = models.CharField(max_length=1, null=True, blank=True) def __str__(self): return self.name serializers.py class WorkoutSerializer(serializers.ModelSerializer): """Serializer for workout objects""" class Meta: model = Workout fields = ['id', 'name', 'description', 'goals', 'workout_time', 'difficulty', 'status', 'created', 'assigned', 'completed', 'rating', 'overall_notes', 'favorited'] read_only_fields = ('id',) views.py class WorkoutListCreateAPIView(generics.ListCreateAPIView): queryset = Workout.objects.all().order_by('assigned').order_by('completed') serializer_class = WorkoutSerializer Why is my code creating empty objects. I've tested through Postman, and was able to create said object. Suggestions? -
Cannot resolve keyword into field. Choices are following, in Django
I have the following models, models.py class Account(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=255, null=True) profile_pic = models.ImageField(null=True, blank=True) ratings = models.FloatField(default=1000) date_joined = models.DateTimeField(auto_now_add=True, null=True) phone = models.CharField(max_length=255, null=True) class Match(models.Model): match_time = models.DateTimeField(null=True) totalPlayers = models.IntegerField(default=2) winner = models.ForeignKey(Account, on_delete=models.SET_NULL, null=True) class Meta: ordering = ['-match_time'] class Participant(models.Model): match = models.ForeignKey(Match, on_delete=models.CASCADE) player = models.ForeignKey(Account, on_delete=models.CASCADE) player_points = models.FloatField(null=True) What I want is basically to write a Query that can return me the following things, Player_Name, Total Matches by Player, Total Points of Player, Matches Won by the Player, Player Ratings I wrote a query like this and it worked great for all the columns above, except Total Points of Player and Matches Won by the Player players = Account.objects.annotate(matches=Count('participant')).order_by('-ratings') So, following the same principle, I tried the following Query to get what I needed exactly, players = Account.objects.annotate(matches=Count('participant'), total_points=Count('player_points'), matches_won=Count('winner')).order_by('-ratings') But this is giving me the following error, Cannot resolve keyword 'player_points' into field. Choices are: date_joined, id, match, matches, name, participant, phone, profile_pic, ratings, user, user_id I unfortunately do not understand how I can get my required result. Can anyone help me reach what I am trying to do?