Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Querying Many To Many relationship in Django
I'm experimenting with Django and I'm trying to figure out Many to Many Relationships. Let's say I have certain model named "Facility", similarly I created another model named "Hotels" which contains fields 'facility' and 'featured_facility' both are in Many To Many relationship with "Facility". I want to add featured_facility only if it is available in 'facility' fields how can I do that? Here is my models code. class Facility(models.Model): name = models.CharField( max_length=100, validators=[validate_facility_name], unique=True, ) description = models.CharField(max_length=100, validators=[validate_facility_description]) can_be_featured = models.BooleanField(default=False) similarly Hotel model is class Hotels(models.Model): hotel_name = models.CharField( max_length=20, unique=True, validators=[validate_hotel_name] facility = models.ManyToManyField( Facility, related_name='hotel_facility', blank=True, ) featured_facility = models.ManyToManyField( Facility, related_name='featured_hotel_facility', blank=True, ) class Meta: default_permissions = () verbose_name = 'Hotel' verbose_name_plural = 'Hotels' def __str__(self): return self.hotel_name Now I want to add 'featured_facility' only if it is available in 'facility' no new featured facility from Facility can be added in 'featured_facility' I am stucked on querying many to many relationship part? -
Django, Only the view permission works, the rest of the permissions do not
First of all, I can't speak English well. test1 account permissions.py from rest_framework import permissions import copy class ViewPermissions(permissions.DjangoObjectPermissions): def __init__(self): self.perms_map = copy.deepcopy(self.perms_map) self.perms_map['GET'] = ['%(app_label)s.view_%(model_name)s'] class AddPermissions(permissions.DjangoObjectPermissions): def __init__(self): self.perms_map = copy.deepcopy(self.perms_map) self.perms_map['POST'] = ['%(app_label)s.add_%(model_name)s'] class UpdatePermissions(permissions.DjangoObjectPermissions): def __init__(self): self.perms_map = copy.deepcopy(self.perms_map) self.perms_map['PATCH'] = ['%(app_label)s.change_%(model_name)s'] view.py from rest_framework import viewsets, permissions, generics from .serializers import PlayerListSerializer from .models import PlayerList from .permission import ViewPermissions, AddPermissions, UpdatePermissions class ListPlayer(generics.ListCreateAPIView): permission_classes = [ViewPermissions, ] queryset = PlayerList.objects.all().filter(del_yn='no').order_by('-key') serializer_class = PlayerListSerializer class AddListPlayer(generics.ListCreateAPIView): permission_classes = [AddPermissions, ] queryset = PlayerList.objects.all().filter(del_yn='no').order_by('-key') serializer_class = PlayerListSerializer class DetailPlayer(generics.RetrieveUpdateDestroyAPIView): permission_classes = [UpdatePermissions, ] queryset = PlayerList.objects.all() serializer_class = PlayerListSerializer Through a simple test I confirmed that I can't see the list without 'view' permission. But for the rest of the permissions I get a '401 (Unauthorized)' error and it doesn't work. I have clearly given the authority right. Can you please let me know where the hell is the problem? Thanks in advance to those who answer. -
File upload with Django form
I am trying to upload video files to vimeo, this is my code views.py def upload_to_vimeo(request): token = 'xxxxx' if request.method == 'POST': video_file = request.POST.get("video_file") v = vimeo.VimeoClient( token=token, ) video_uri = v.upload(video_file) print(video_uri) return redirect('home') return render(request, 'forms/video_upload_form.html', {}) template <form action="." method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file"> <input type="submit" class="button" value="Upload"> </form> but it throws error AttributeError at /upload_to_vimeo/ 'NoneType' object has no attribute 'read' but I can directly upload without a form as follows v = vimeo.VimeoClient( token=token, ) video_uri = v.upload('client_admin/test1.mp4') How I can do it with a form, any help -
Getting all the users name who liked a post in django
I am trying to show the List of Users who Liked a Particular Post. Here is what I have tried but nothing is showing. I have created the post_likes in the views.py and tried to loop through its users in the post-details.html: Here is the post_detail.html template: {% for user in post_likes %} <p>{{ user.username }}f</p> {% endfor %} but nothing is showing. Here is the Post Models.py: class Post(models.Model): content = RichTextUploadingField(null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author') likes = models.ManyToManyField(User, related_name='liked', blank=True) Here are the like model.py: class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=8) Here are the views.py: class PostDetailView(DetailView): model = Post template_name = "blog/post_detail.html" # <app>/<model>_<viewtype>.html def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter( post=post).order_by('-id') total_likes = post.total_likes() liked = False if post.likes.filter(id=self.request.user.id).exists(): liked = True if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) --------Comment Related Lines-------------------------------- else: comment_form = CommentForm() context["comments"] = comments context["comment_form"] = comment_form context["total_likes"] = total_likes context["liked"] = liked return context def get(self, request, *args, **kwargs): res = super().get(request, *args, **kwargs) self.object.incrementViewCount() if self.request.is_ajax(): context = self.get_context_data(self, *args, **kwargs) html = render_to_string('blog/comments.html', context, request=self.request) return JsonResponse({'form': … -
horizontal multiselect checkboxes in django admin
Hopefully this is a simple fix, although I haven't found anything through searching. I am using this code in admin.py to make my manytomany field appear as checkboxes in admin. class MyModelAdmin(admin.ModelAdmin): formfield_overrides = { models.ManyToManyField: {'widget': CheckboxSelectMultiple}, } But, I have about 10 choices, which is annoying as a vertical list. Is there a way to get the checkboxes to display horizontally or even more flexibly as 2 columns of five choices (or some other arbitrary look)? -
Best approach to an API update project
I'm working in a personal project to segment some data from the Sendinblue Api (CRM Service). Basically what I try to achieve is generate a new score attribute to each user base on his emailing behavior. For that proposed, the process I've plan is as follows: Get data from the API Store in database Analysis and segment the data with Python Create and update score attribute in Sendin every 24 hours The Api has a Rate limiting 400 request per minute, we are talking about 100k registers right now which means I have to spend like 3 hours to get all the initial data (currently I'm using concurrent futures to multiprocessing). After that I'll plan to store and update only the registers who present changes. I'm wondering if this is the best way to do it and which combinations of tools is better for this job. Right now I have all my script in Jupyter notebooks and I recently finished my first Django project, so I don't know if I need a django app for this one or just simple connect the notebook to a database (PostgreSQL?), and if this last one is possible which library I have to learn … -
why json response is returning nothing?
Here I am using django 3.0.3. i have two question here. 1-you can see in terminal output json response is equal to {} brackets, i don't its not returning api data. and at the send i am using condition where set if there is json response than redirect that condition is becoming true but not redirecting to the desire template or page. 2-i am trying to redirect template landpage to dashboard page but with my code that is not working. I search about this but got nothing helpful so now I am asking this question maybe you guys can figure out. you will understand more better once you see code below and the output from terminal is also mentioned below. views.py def get(self, request): # <view logic> output = self.request.GET.get('hash', None) print('print',output) if output is not None: print("Hash",output) print('Proper url =',f'https://api.shasta.tronscan.org/api/transaction-info?hash={output}') response = requests.get(f'https://api.shasta.tronscan.org/api/transaction-info?hash={output}') print('Resposne =',response) # session = requests.Session() # response = session.get(f'https://api.shasta.tronscan.org/api/transaction-info?hash={output}') print('Response.header =',response.headers['content-type']) print('Response.json =',response.json) print('Response.json =',response.json()) json = response.json() if response.json() is not None: print('condition is true') return redirect('dashboard') # return JsonResponse(response.json()) return render(request, self.template_name, {}) output in terminal Hash 0850eb3e2428f870209b53ffdb0000000000000000000 Proper url = https://api.shasta.tronscan.org/api/transaction-info?hash=0850eb3e2428f870209b53ffdb0000000000000000000 Resposne = <Response [200]> Response.header = application/json;charset=utf-8 Response.json = <bound method … -
DOS attacks in Django?
I wanted to know how Denial of Service attack and XSS attacks are handled in Django? I tried reading it on official site, but still it's not clear . -
Printing out dictionary values from Python to HTML
Hey guys I'm trying to figure out how to print the values from newqueries, which I get from view.py. Why am I able to print out the values in the loop but not outside of them? What is the correct syntax to print out the username of newquery. Right now I'm getting this error when I try to print out the way below, which I know is wrong: Could not parse the remainder: '[0].username' from 'newqueries[0].username' Any ideas? view.py: def profile(request, username): userSearch = User.objects.get(username = username) userID = userSearch.id newquery = NewPost.objects.filter(username = username) followersCount = Follow.objects.filter(following_id = userID).count() return render(request, "network/profile.html", {'followers_count': followersCount, 'newqueries': newquery}) profile.html: {% extends "network/layout.html" %} {% block body %} <h2>{{user.username}}'s Profile</h2> <h1>{{newqueries[0].username}}</h1> <input type="button" value="Follow" id="followButton"> <p>Followers: <span id="followers">{{ followers_count }}</span></p> <p>Follows: </p> {% for newquery in newqueries reversed %} <div class="newpost"><p>{{ newquery.body }}</p><p>By: {{ newquery.username }} on: {{ newquery.timestamp }} Likes: {{ newquery.likes }}</p> {% endfor %} </div> {% endblock %} -
Why does sending a delete request trigger the get_queryset() Django method?
I am having trouble sending a delete request from axios to my Django backend. With axios I call delete in the following way for many of my models: // DELETE DAY export const deleteDay = (day_id) => (dispatch, getState) => { axios .delete(`/api/days/${day_id}/`, tokenConfig(getState)) ... The value of tokenConfig(getState) is just: { headers: { Authorization: "Token 032b2f569037f0125753ef8f67e7774d34a756646ae28cefd54eb1c54bd0b149" Content-type: "application/json" } } In my api.py file I have many viewsets which use my predefined model and serializer objects. The viewset that should catch this request is the DayViewSet. I followed a guide to create all of these viewsets and from what I could find online, it seems that the guide I used uses GenericAPIView functions. For this reason I've been using functions like perform_create, get_queryset, etc. I have been able to successfully call this deleteDay function, and it would just delete the instance of the object based on the day_id I gave it, but recently, after changing my get_queryset function, it seems that a strange issue has arisen. Now, when I call the deleteDay function, it calls my get_queryset function instead of whatever is normal. Here is the DayViewSet object: class DayViewSet(viewsets.ModelViewSet): permission_classes = [ permissions.IsAuthenticated ] serializer_class = DaySerializer def … -
django - combine two tables in one in views.py for using in template
There are two models: class Person(models.Model): id = models.IntegerField(primary_key=True) firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) class Job(models.Model): title = models.CharField(max_length=100) and here are the data in them: table A: +---+--------+-------+ | 1 | Alex | King | +---+--------+-------+ | 2 | Jo | Ford | +---+--------+-------+ | 3 | Bill | Arm | +---+--------+-------+ | 4 | Donald | Black | +---+--------+-------+ Table B: +---+-----+ | 1 | X | +---+-----+ | 2 | XL | +---+-----+ | 3 | S | +---+-----+ | 4 | XXL | +---+-----+ What I want to get in template is a result like this: +---+--------+-------+-----+ | 1 | Alex | King | X | +===+========+=======+=====+ | 2 | Jo | Ford | XL | +---+--------+-------+-----+ | 3 | Bill | Arm | S | +---+--------+-------+-----+ | 4 | Donald | Black | XXL | +---+--------+-------+-----+ The foreignkey is the id. I know annotate may wok here but I do not know how to use it, and the examples on the internet are not so clear. I want to use it in a for loop to get the result like this: {% for field in combined %} <td>{{ field.id }}</td> <td>{{ field.firstname }}</td> <td>{{ … -
Django: Making a value in a model unique specific to a user
I have a model for a project: class Project(models.Model): name = models.CharField(max_length=200, unique=True) user = models.ForeignKey(User, on_delete=models.CASCADE) I want to make the project name a unique value per user but at the moment if user 1 creates a name of "project 1" then user 2 is unable use that project name. What is the best way to go about this? Thanks! -
Django Dynamic EditView for a model
I have a Table: I want to create an EditView for particular Type like shown below: When user edits values for C1 & C2 I want my EditView to save it back into my table for Type=T1. Do I write a custom TemplateView? I dont know how to use FormSet in this scenario. Thanks -
Input model value by operation Django
I'm trying to input a model form by operation in Django, but i really don't know how to do it... Here is my code, where profit should be (valorContrato - valorGasto) I also would like that the user couldn't input anything manually in this field models.py class Contrato(models.Model): nome = models.CharField(max_length=60) bioContrato = models.TextField(null=True, blank=True) cliente = models.ForeignKey(Cliente, on_delete=models.SET_NULL, null=True) valorContrato = models.FloatField(max_length=45, null=True, blank=True) valorGasto = models.FloatField(max_length=45, null=True, blank=True) profit = models.FloatField(max_length=45, null=True, blank=True) dataContrato = models.DateField(null=True, blank=True) dataEntrega = models.DateField(null=True, blank=True) arquivos = models.FileField(upload_to='arquivos_contratos', null=True, blank=True) def __str__(self): return self.nome -
Is it okay to use the same Redis store for both cache and django-channels channel layer in Django?
I have a Django 3.1 app that uses Redis for its cache backing store (django-redis). I wish to use django-channels, which has the ability to use Redis for channel layers. Is it safe or unsafe to use the same Redis store for both? In other words, I wish to have the following in my settings.py, and I want to know if that's okay. import environ env = environ.Env() REDIS_HOST = env('REDIS_HOST', default='127.0.0.1') REDIS_PORT = env('REDIS_PORT', default='6379') CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', "LOCATION": "redis://" + REDIS_HOST + ":" + REDIS_PORT + "/0", 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', 'CONNECTION_POOL_KWARGS': {'max_connections': 30}, 'IGNORE_EXCEPTIONS': True, } } } CHANNEL_LAYERS = { "default": { 'BACKEND': 'channels_redis.core.RedisChannelLayer', "CONFIG": { "hosts": [(REDIS_HOST, int(REDIS_PORT))], }, } } -
Django html table - how to specify/locate a certain cell?
new to django and everything. I'm trying to figure out how to specify or locate a certain cell in a html table. I would like to change the background color of certain cells if certain conditions are met based on the generated grid. I've registered a simple_tag, and I would like to be able to tell it which cell to change. For example, if value of row 3, column 4 == x, then apply red background; or find cell of row 2, column 5, etc. How do I address it? Here's a simplified version of what I've done so far: from views.py: list1 = [a,b,c,d,e,f] # this is basically what the table (grid) looks like list2 = [b,c,a,d,f,e] list3 = [f,a,e,d,c,b] list4 = [c,d,a,b,f,e] list5 = [d,e,b,a,f,c] list6 = [e,b,a,c,d,f] grid = [list1, list2, list3, list4, list5, list6] result1 = [0, 1, 2] result2 = [4, 5] results = [result1, result2] .html {% for var in grid %} <table> <tr> <td class='{% bg_color var.0 %}'>{{ var.0 }}</td> <td class='{% bg_color var.1 %}'>{{ var.1 }}</td> <td class='{% bg_color var.2 %}'>{{ var.2 }}</td> <td class='{% bg_color var.3 %}'>{{ var.3 }}</td> <td class='{% bg_color var.4 %}'>{{ var.4 }}</td> <td class='{% bg_color var.5 %}'>{{ … -
Design question: How would you design a temporary user table?
I am in the process of designing a website that would allow sports coaches to create teams, and then add players to that team. The goal is to allow coaches to add players to their team and associate stats to them by entering match data. The issue I'm running into is the ability for players to create their own account and link their account to one of the players the coach made. The coach would be able to enter a player account's unique ID and select a player he created on the team, and give the player access to the stats he entered for the 'fake' user. The fake user would be deleted at this point. My initial design for tackling this is as follows: I will use the default 'Users' table, and link it to a 'Profile' table via a OneToOneField. Whenever a coach creates a player for their team, a user will be created and an associated profile. The fake user would have a UUIDField as an ID in the Profile table. I'm storing the stats for players as follows: class Stats(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) match = models.ForeignKey(Match, on_delete=models.CASCADE) player = models.ForeignKey(User, on_delete=models.CASCADE) ... ... several … -
COPY failed: stat /var/lib/docker/tmp/docker-builder713892078/requirements.txt: no such file or directory
When i build Dockerfile sudo docker build . Copy command inside simple Dockerfile fail. Operating system is Ubuntu Dockerfile: FROM python:3.8-alpine MAINTAINER mojtaba nafez ENV PYTHONUNBUFFERD 1 COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt RUN mkdir /app WORKDIR /app COPY ./app /app RUN adduser -D user User user the folder "/var/lib/docker/tmp" in my ubuntu system is empty! Output of build Command that's mentioned above is: Sending build context to Docker daemon 68.61kB Step 1/10 : FROM python:3.8-alpine ---> ff6233d0ceb9 Step 2/10 : MAINTAINER mojtaba nafez ---> Using cache ---> 45e8f256f9ce Step 3/10 : ENV PYTHONUNBUFFERD 1 ---> Using cache ---> dec1458c5753 Step 4/10 : COPY ./requirements.txt /requirements.txt COPY failed: stat /var/lib/docker/tmp/docker-builder733337810/requirements.txt: no such file or directory requirements.txt: Django>=2.2.0,<=3.1.2 djangorestframework>=3.9.0,<3.10.0 Dockerfile and requirements.txt are in the same folder -
Hide components in Django Forms
I am currently working on a django project and I would like to be able to hide some components in the form until the user triggers it. I decided to use the form manually and I have not been able to get the desired results. Below is an image of the form in it simplest state I would want the page to load with only 'First Name', 'Last Name' and 'Your Choice' displaying and the choice of the user should trigger either 'Your Hostel' or 'Your City' to pop up. Below is the manual form <form method="post" class="order-form"> {{ form.non_field_errors }} <div id="first" class="fieldWrapper"> {{ form.first_name.errors }} <label for="{{ form.first_name.id_for_label }}">First Name:</label> {{ form.first_name }} </div> <div id="last" class="fieldWrapper"> {{ form.last_name.errors }} <label for="{{ form.last_name.id_for_label }}">Last Name:</label> {{ form.last_name }} </div> <div id="option" class="fieldWrapper"> {{ form.delivery_option.errors }} <label for="{{ form.delivery_option.id_for_label }}">Your Choice:</label> {{ form.delivery_option }} </div> <div id="hostle" class="fieldWrapper"> {{ form.hostel.errors }} <label for="{{ form.hostel.id_for_label }}">Your Hostel:</label> {{ form.hostel }} </div> <div id="city" class="fieldWrapper"> {{ form.city.errors }} <label for="{{ form.city.id_for_label }}">Your City:</label> {{ form.city }} </div> Can someone kindly help me. I'm new to this environment. Thanks in advance -
django: validate count of a many to many relation before saving to database
I'm a little bit stuck in my django project. I want to do the following: I have two models(unnecessary parts left out): models class UserGroup(models.Model): max_users = IntegerField() @property def user_count(self): return len(self.user_set.objects.all()) class User(models.Model): groups = models.ManyToManyField(UserGroup) forms class RegisterForm(ModelForm): class Meta: model = user fields = ['usergroup'] widgets = {'usergroup': CheckboxSelectMultiple()} def clean_usergroup(self): qs = self.cleaned_data['usergroup'] a = len(qs) if len(qs) > 2: raise ValidationError("Your group limit is 2") return qs The UserGroups can be defined, usually there are 3 to 5 and each UserGroup has a maximum of users that can join it. However a user is able to join multiple groups, but he should be restricted to join 2 groups at maximum. The user can choose his groups via a ModelForm which is generated from the User Model. My approach was to override the clean() method of the form and the clean_groups() of the form, but I always ran into the problem, that when the form is reloaded I get an Exception: ValueError: "<User: User object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used. I know this makes sense since there isn't a saved m2m relation that can … -
Where is the error? Why average_rank does not displayed?
Friends , where is the problem , average_rank does not diasplayed in GET response My Models.py class Car(models.Model): Make_Name = models.CharField(max_length=100) Model_Name = models.CharField(max_length=100) class Rating(models.Model): RATING_CHOICES = ( (1,'1'), (2,'2'), (3,'3'), (4,'4'), (5,'5'), ) rating = models.IntegerField(choices=RATING_CHOICES) car = models.ForeignKey(Car,on_delete=models.CASCADE,related_name='rating') Views.py class CarViewSet(ListCreateAPIView): serializer_class = CarSerializers def get_queryset(self): queryset = Car.objects.all() Car.objects.aggregate(average_rank = Avg('rating__rating')) return queryset serializers.py: class CarSerializers(serializers.ModelSerializer): average_rank = serializers.DecimalField(read_only=True,decimal_places=1,max_digits=10) class Meta: model = Car fields = ['Make_Name','Model_Name','average_rank'] -
Posting Base64 with Axios cause [Errno 54] Connection reset by peer
I am currently working on a web-application using VueJS for the front-end and Django (Django Rest Framework) for the back-end. One of the feature of the application is to send a pdf invoice by mail. So I was able to generate the pdf using "jspdf" library. And on Django side, I made an API end-point in order to send an email (with the pdf attached). So the logic is (tell me if it's wrong to do that): Converting the output pdf to Base64 on the front-end in order to post it to my "sendmail" endpoint with Axios. Decoding the Base64 string on the back-end, write a temp pdf file, and attached it to send the mail. It works perfectly, I tested it, the post request have a status 200. I receive the mail with the pdf attached... But on django side, I got "[Errno 54] Connection reset by peer". Here's the full error: [24/Nov/2020 21:50:53] "POST /api/sendmail/ HTTP/1.1" 200 0 -------------------------------------------- Exception happened during processing of request from ('127.0.0.1', 59267) Traceback (most recent call last): File "/Users/jjj/anaconda3/lib/python3.6/socketserver.py", line 639, in process_request_thread self.finish_request(request, client_address) File "/Users/jjj/anaconda3/lib/python3.6/socketserver.py", line 361, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Users/jjj/anaconda3/lib/python3.6/socketserver.py", line 696, in __init__ self.handle() File … -
Create a one to many relationship with Django
Hey guys I'm making a social media app and I have a User table with the generic User Model from Django used. I'm now creating a Follow table where I want to keep track of the different usernames the user follows and a count of those following him (I don't need to display the names for the followers field just the amount of followers a user has). How would I go about doing this? Right now this is what I have, but I'm unable to view the actual data in the database so I'm not sure how it works. Is there a column for username that is borrowed from the User model? I can't find solid information on how this works. from django.contrib.auth.models import AbstractUser from django.contrib.postgres.fields import ArrayField from django.db import models class User(AbstractUser): pass class Follow(models.Model): followers = models.IntegerField(default=0) following = models.ForeignKey(User, related_name = 'follow_to_set', on_delete = models.CASCADE) class NewPost(models.Model): username = models.CharField(max_length=64) body = models.CharField(max_length=64) likes = models.IntegerField(default=0) timestamp = models.DateTimeField(auto_now_add=True) -
Django REST serialize customizing field mapping group by date
Problem: Not able to group my JSON output by date I am serializing a model and getting this output: [ { "date": "2020-11-24", "name": "Chest", "workout": { "name": "Chest", "exercise": 1, "repetitions": 10, "weight": 80 } }, { "date": "2020-11-24", "name": "Chest", "workout": { "name": "Chest", "exercise": 1, "repetitions": 10, "weight": 85 } }, { "date": "2020-11-24", "name": "Chest", "workout": { "name": "Chest", "exercise": 1, "repetitions": 10, "weight": 90 } }, I want to get it like the JSON below and group it by date. [ { "date": "2020-11-24", "workout": { "name": "Chest", "exercise": 1, "repetitions": 10, "weight": 80 }, "name": "Chest", "exercise": 1, "repetitions": 10, "weight": 85 }, "name": "Chest", "exercise": 1, "repetitions": 10, "weight": 90 }, } ] I have one model: class WorkoutLog(models.Model): date = models.DateField() name = models.CharField(max_length=50) #When save() name = Workout.name exercise = models.ForeignKey('Exercise', related_name='log', on_delete=models.CASCADE) repetitions = models.IntegerField() weight = models.IntegerField() Trying to serialize and group the JSON by date: class WorkoutLogSerializer(serializers.ModelSerializer): class Meta: model = WorkoutLog fields = ['date', 'workout'] workout = serializers.SerializerMethodField('get_workout') def get_workout(self, obj): return { 'name': obj.name, 'exercise': obj.exercise_id, 'repetitions': obj.repetitions, 'weight': obj.weight, } The code lets me custom the field layout, but not really grouping it by date. … -
Running Pillow Django Python
I Have a Django project working just fine on my windows machine with python 3.6 and now I am trying to run my Django code on this iOS machine but sadly when I run pip3 to instal my requirements it prints this error: Running setup.py install for Pillow ... error ERROR: Command errored out with exit status 1: command: /Library/Frameworks/Python.framework/Versions/3.9/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/tr/0bxqz_fn6f9b9pjfcykhrwnr0000gn/T/pip-install-nlvm4jl5/pillow/setup.py'"'"'; __file__='"'"'/private/var/folders/tr/0bxqz_fn6f9b9pjfcykhrwnr0000gn/T/pip-install-nlvm4jl5/pillow/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/tr/0bxqz_fn6f9b9pjfcykhrwnr0000gn/T/pip-record-3zn9ygo2/install-record.txt --single-version-externally-managed --compile --install-headers /Library/Frameworks/Python.framework/Versions/3.9/include/python3.9/Pillow cwd: /private/var/folders/tr/0bxqz_fn6f9b9pjfcykhrwnr0000gn/T/pip-install-nlvm4jl5/pillow/ Complete output (172 lines): running install running build running build_py creating build creating build/lib.macosx-10.9-x86_64-3.9 creating build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/MpoImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImageMode.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/PngImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/XbmImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/PcxImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/SunImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImageFile.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/SpiderImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/TarIO.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/FitsStubImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/MpegImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/BdfFontFile.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/GribStubImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImageStat.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/PixarImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/GimpPaletteFile.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImageColor.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ContainerIO.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/MspImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/MicImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/_version.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImtImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/GifImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/PalmImagePlugin.py -> build/lib.macosx-10.9-x86_64-3.9/PIL copying src/PIL/ImageQt.py -> build/lib.macosx-10.9-x86_64-3.9/PIL …