Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to search whether a value is present in a list of values in Django
In my model a list of values is stored. Now a user can enter a list of values and if any of the values is present in the table then that record should be fetched. For e.g. a user enters [3, 63, 2, 5]. Now suppose the list that is present in the table has values [65, 5, 8, 48]. Since the input list which is [3, 63, 2, 5] has got a common value which is 5 in this case I should get this record. This is the column which is present in my model. The model name is Room. room_number = models.CharField(validators=[validate_comma_separated_integer_list], max_length=4000) I don't understand how I can do this. Can someone please help me with this? I can get an individual value and run a for loop for every value present in the input list. but I don't understand how I can search whether a given value is present in the list. -
How i can split a Email in Django
Good morning I've been sitting for 5 hours on what should be a simple problem. I would be grateful if you could end my suffering. It is about a dashboard page. I want the user to be greeted with his name (Hello, ....) after he has registered with his email address. When registering, the email address is always the same, name.example@hotmail.de. I want to split the email address and display only the name, but I can only manage to display the whole email address. view.py @login_required(login_url='login') def Example_dashboard(request): form = MembersForm() current_user = request.user #current_user.split is not working! context = {'form': form, "cunrrent_user": current_user} return render(request, 'example_dashboard.html', context) html <p>Welcome, {{ current_user}} </p> <form action='' method='POST'> {%csrf_token%} {{ form }} models.py class Members(models.Model): email = models.CharField(max_length=200, null=True) passwort = models.CharField(max_length=200, null=True) forms.py class MembersForm(ModelForm): class Meta: model = Members fields = ["studiengang", "kategorien"] -
Passing value from a form to get method in django
I want to pass the value in the comment text area when the a tag is clicked.Is there any other methods to pass both the comment and rating into the get method.I saw some similar questions but the answers where suggesting to use hidden input field to pass the value.But in my case i want the rating number in the clicked tag too.so i won't be able to use the hidden input method. <form method='post'> <div class="container-fluid py-4"> <div class="row"> <div class="col-lg-6 mx-auto mb-lg-0 mb-4"> <div class="card"> <div class="card-body p-4"> <h4 class="font-weight-bolder">Review</h4><br> <div > <textarea class="textarea p-3 w-100" placeholder="Write a review" cols = "40" rows="5"></textarea> {{form.comment}} </div> </div> </div> </div> </div> <div class="container-fluid py-4"> <div class="row"> <div class="col-lg-6 mx-auto mb-lg-0 mb-4"> <div class="card"> <div class="card-body p-4"> <h4 class="font-weight-bolder">Rating</h4><br> <div class="rating rating2"> <a href="{% url 'ratings' 5 id %}" title="Give 5 stars" data-value="5" type="submit">★</a> <a href="{% url 'ratings' 4 id %}" title="Give 4 stars" data-value="4" type="submit">★</a> <a href="{% url 'ratings' 3 id %}" title="Give 3 stars" data-value="3" type="submit">★</a> <a href="{% url 'ratings' 2 id %}" title="Give 2 stars" data-value="2" type="submit">★</a> <a href="{% url 'ratings' 1 id %}" title="Give 1 star" data-value="1" type="submit">★ </a> </div> </div> </div> </div> </div> </div> </form> -
Django models with key and multiple value choices
im trying to work my way into making an api oriented webapp with Django and i wanted to create a model where i can choose a day and a time for that day. So my first thought was to make a model with an atttibute that can stored set day with a set time, this last one being of multiple choice, like a dictionary or something. My motive is to save those values as attributes in my DB but i dont really know if thats possible! Thx a lot beforehand. Something like this came to my mind: class Reservation(models.Model): reservation = ({'monday':[10,11,12,13,14,15,16,17], 'tusday':[10,11,12,13,14,15,16,17], 'friday':[10,11,12,13,14,15,16,17]}) -
DRF Swagger - Endpoint parameter doesn't match the Serializer
So I'm trying to create at REST API using DRF and Swagger for API Documentation, But I notice that Swagger UI Parameter doesn't match the given Serializer. MailSerializer.py ` from main.BusinessLayer.Model.Mails import Mails from rest_framework import serializers class MailSerializer(serializers.Serializer): class Meta: model = Mails fields = '__all__' # Mail Properties Subject = serializers.CharField(max_length = 30, allow_blank = False) Sender = serializers.CharField(max_length = 30, allow_blank = False) Recipients = serializers.CharField(allow_blank = False) ReplyToAddress = serializers.CharField(max_length = 30) Importance = serializers.CharField(max_length = 30, allow_blank = False) ApplicationId = serializers.CharField(max_length = 30, allow_blank = False) # Mail Content Body = serializers.CharField(allow_blank = False) Attachments = serializers.CharField(allow_blank = False) # Other Parameters UseDefaultHeader = serializers.IntegerField(default = 0) UseDefaultFooter = serializers.IntegerField(default = 0) def create(self, validated_data): return Mails.objects.create(**validated_data) ` @swagger_auto_schema( operation_description="", operation_summary="create a mail", request_body=MailSerializer ) def create(self, request, *args, **kwargs): try: serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) return Response({ 'code': 200, 'success': True, 'message': '%s successfully created.' % (OBJECT_NAME), 'data': [] }, status= status.HTTP_200_OK) I tried to use @swagger_auto_schema and a request_body parameters, but still not working -
old_field = model_state.fields.pop(self.name) KeyError: when migrations
I got this error $python manage.py makemigrations System check identified some issues: WARNINGS: ?: (urls.W002) Your URL pattern '/<int:pk>/edit' [name='line-bot-edit'] has a route beginning with a '/'. Remove this slash as it is unnecessary. If this pattern is targeted in an include(), ensure the include() pattern has a trailing '/'. shared_models.ScenarioTemplate.user_types: (fields.W340) null has no effect on ManyToManyField. Traceback (most recent call last): File "/Users/whitebear/MyCode/httproot/nice_cdk/cinema-admin/manage.py", line 29, in <module> main() File "/Users/whitebear/MyCode/httproot/nice_cdk/cinema-admin/manage.py", line 25, in main execute_from_command_line(sys.argv) File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/core/management/commands/makemigrations.py", line 149, in handle loader.project_state(), File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/db/migrations/loader.py", line 335, in project_state return self.graph.make_state(nodes=nodes, at_end=at_end, real_apps=list(self.unmigrated_apps)) File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/db/migrations/graph.py", line 315, in make_state project_state = self.nodes[node].mutate_state(project_state, preserve=False) File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/db/migrations/migration.py", line 89, in mutate_state operation.state_forwards(self.app_label, new_state) File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/db/migrations/operations/fields.py", line 162, in state_forwards old_field = model_state.fields.pop(self.name) KeyError: 'is_year_set' even $python manage.py migrate shows the same error. The checks I have done. $python manage.py showmigrations Every migrations are applied, but I have done python manage.py migrate --fake before error happens. in models.py is_year_set is … -
Im trying to download a file and i need to send option to my Django view from js script . Please advice
My HTML page looks something like below: The post function used is for upload the file with edited data..! Im trying to get the option value from HTML page to my Django view. <div><h3 style="text-align: center">Bulk Upload</h3></div> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="col-md-4"> <select class="form-select form-control" style="padding: 3px; border-radius: 1px;" id="option" name="option"> <option selected value="0"> Please select operation</option> <option value="1">Insert New Source Client</option> <option value="2">Update Volcker Attribute</option> </select> </div> <div class="col-md-2"> {% csrf_token %} <button id="downloadBtn" type="submit" title="Download CSV Template" onclick="export_template()" class="btn btn-primary" style="height: 34px; width: 100px" > Download </button> </div> My javascript function is defined as below: function export_template(){ let option = document.getElementById('option').value; console.log(option) if (option!=""){ window.location.href="export_template/option="+option; } } The view defined is as below where im trying to fetch "option" from JS script please advice def export_template(request, post): #option = int(request.POST.get("option")) option = int(request.POST.get("option")) if option == 2: file = open('C:/Users/Desktop/New Project (2) (1)/New Project/uploadcsv/media/bulk_upload/Update_Client_YYYYMMDD.csv', 'r') response = HttpResponse(file, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=Update__YYYYMMDD.csv' return response How to pass JS script value as parameter to my Django view..!` -
Django User Registration Form not working, no error
Trying to create a simple user registration form in django. Here is my views.py- def registerPage(request): form=UserCreationForm() if request.method == 'POST': form=UserCreationForm(request.POST) if form.is_valid(): form.save() context = {'form':form} return render(request, 'newapp/register.html', context) And my html template- <h3>Register</h3> <form method="POST" action=""> {% csrf_token %} {{form.as_p}} <input type="submit" name="Create User"> </form> In the views I imported UserCreationForm like this and following is the url which is working fine- from django.contrib.auth.forms import UserCreationForm url- path('register/', views.registerPage, name="register"), When I try to create a user the form seems to work fine but the user is never created in the admin. It doesn't show up.I refreshed the page and all. There is no error. I created a user from the admin panel just to make sure and it works. Earlier same form was giving me a CSRF token failure. Rebooting the computer that error went away. Now no error, but also no user. Curious with no error in sight, when can be reason for this to happen? Here is how the CMD looks like after few attempts of user creation, see if that gives you any clue- -
How to add SVG as background image in Django template
Pls how can I add SVG as background image in Django I have tried and it's not working I added the svg in this format url("image.svg") but nothing is showing. -
Django raise custom error if invalid API parameters
I am writing an API endpoint that queries for an Event in the time window given. The Event model has a start and end time, and the query accepts a search start time and an search end time. Any Event that overlaps between these two windows is returned. This works well. However, if the user asks to search using a search_time_start that is after the search_time_end, it returns no results (obviously), with no indication why. Instead I would like to return an Error message indicating what is wrong. I have a rough idea of how to do this, but not how to plug it into my existing code. Model class Event(models.Model): name = model.CharField(max_length=64) start_time = models.DateTimeField(null=False) end_time = models.DateTimeField(null=False) Serializer class EventSerializer(serializers.ModelSerializer): start_time = serializers.DateTimeField() end_time = serializers.DateTimeField() class Meta: model = Event fields = ("start_time", "end_time") Filter and View class EventFilterSet(GeoFilterSet): search_time_start = DateTimeFilter( field_name="end_time", lookup_expr="gte", help_text=( "The time for the start of the search. Limits events to those that end after the start time." ), ) search_time_end = DateTimeFilter( field_name="start_time", lookup_expr="lte", help_text=( "The time for the end of the search. Limits events to those that start before the end time." ), ) class Meta: model = Event … -
Saving a record along with the logged in users group in Django
I am new to Django. I want to save the logged in users Group in the groups field upon adding a new record. models.py from django.contrib.auth.models import User, Group, Permission class Infringement (models.Model): name = models.CharField(max_length=200) link = models.CharField(null=True, blank=True, max_length=200) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) infringer = models.ForeignKey(Infringer, on_delete=models.SET_NULL,null=True) player = models.ForeignKey(Player, on_delete=models.SET_NULL,null=True) status = models.ForeignKey(Status, on_delete=models.SET_NULL,null=True) groups = models.ForeignKey(Group, on_delete=models.CASCADE,default=1) views.py @login_required(login_url='login') def createInfringement(request): form = InfringementForm() if request.method == 'POST': form = InfringementForm(request.POST) if form.is_valid(): form.instance.groups = 'request.user.group' form.save() return redirect('home') context ={'form': form} return render (request, 'base/infringement_form.html', context) forms.py class InfringementForm(ModelForm): class Meta: model = Infringement fields = ['name', 'link', 'infringer', 'player'] Based on my research, I tried adding this in the view but it doesn't work. form.instance.groups = 'request.user.group' -
Updating environmental variables in Django while running
I have an app that makes some API calls, I store my API secret in an .env file which is loaded into the Django settings file which works fine. Once a month I have to update the API secret, I have the code to check for expiry and get the new key, my question is how to handle that within my running Django app. As it stands I can load the .env file in and do a find a replace on the key but that feels like a bad way to go about it in addition to not taking effect until the next time the app is restarted. When you have secrets that change over time whats best practice on updating and storing them? -
username and log out not appeared while logging in with google
I have made my models for customer, merchant. models.py class CustomUser(AbstractUser): is_customer = models.BooleanField(default=False) is_merchant = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) class Customer(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, related_name = 'customer', null=True, blank=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) username = models.CharField(max_length=255) email = models.EmailField(max_length=255) phone_number = models.CharField(max_length=12) address = models.CharField(max_length=255) profile_pic=models.FileField(default="") created_at=models.DateTimeField(auto_now_add=True) def __str__(self): return self.username When a customer log in to the app they see their username in navbar and the "log in" button turns out to "log out". Now I want to give customers the functionality to log in with google too. settings.py ALLOWED_HOSTS = ['localhost'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'projectapp.apps.ProjectappConfig', 'django_extensions', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.facebook', ] SITE_ID=1 LOGIN_REDIRECT_URL = '/' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'reward_database', 'USER': 'postgres', 'PASSWORD': 'ReVerSe@05', 'HOST': 'localhost', 'PORT': '5432' } } AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ] SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', } } } For that purposes I have a signal.py. @receiver(post_save, sender = CustomUser) … -
Django - display value of an @property field in a filter
Good evening guys, I have the following model structure in my project: ` class Foo(models.Model): foo_name = models.TextField() foo_city = models.TextField() foo_actions = models.ManyToManyField(Action, through="FooActions") @property def bar(self): response = True if FooAction.objects.filter( foo_id=self.pk, foo__action=Action.ACTION_NAME_PK).first() else False return response ` I need to bring the 'bar' field in a filter, but I'm not getting it. I tried as follows: Foo.objects.filter(nome="João").values("foo_city","bar") Is it possible to bring this information this way? PS.: Sorry for my bad english -
Run python script at the click of an html button (Flask/Django)
I have a very simple python code that retrieves the share price of some stocks. I have managed to include that in Django/Flask so I can see this in a html page. I would like to create an html button that when I click on it it runs the python script and the share prices refresh (and remain on the same html page e.g. index.html) however I can't make it work. Can you please help with the html code for the button and the piece of code that I need to add to the app to make it work? -
Django - How to add a comment limit of 1
I currently have a comment functionality and I want to add a limit of one comment for each user but don't know how to do that. I tought on making a 'posted' field in the user model which would be true when the user posted a comment but I don't know how to do that and most importantly if that is the better way of doing that... class Comment(models.Model): service = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True,) content = models.CharField(max_length=200, null=False, blank=True) def get_absolute_url(self): return reverse('product-feedback', kwargs={'pk': self.pk}) class ProductFeedbackView(DetailView): model = Product template_name = 'services/product-feedback.html' def get_context_data(self , **kwargs): data = super().get_context_data(**kwargs) connected_comments = Comment.objects.filter(service=self.get_object()) number_of_comments = connected_comments.count() data['comments'] = connected_comments data['no_of_comments'] = number_of_comments data['comment_form'] = CommentForm() return data def post(self , request , *args , **kwargs): if self.request.method == 'POST': comment_form = CommentForm(self.request.POST) if comment_form.is_valid(): content = comment_form.cleaned_data['content'] new_comment = Comment(content=content, author=self.request.user , service=self.get_object()) new_comment.save() return redirect(self.request.path_info) <form action="" method="POST" id="main_form" class="comment_form"> <div> <label for="comment">Type Comment here</label> {{ comment_form.content }} {% csrf_token %} <input type="submit" value="Post"></div> </div> </form> -
How to deal with users when they are authenticated externally via openid recieving only an access or id token?
How do you for example create a model with a foreignkey to a user when the user is authenticated via openid connect externally recieving access token and id token after login or signup? How is authorization (roles, groups, permissions) done when we are not using standard Django authentication or user models but where these tokens (containing a sub or object id) exists in the session? Thanks for your time and help. -
Getting graphQl to work with django mongoengine and graphene
When trying to connect to graphQl, i am met with this error. AssertionError at /graphql/ You need to pass a valid Django Model in ProductType.Meta, received "<class 'inventory.models.Product'>". I am using Django, mongoengine and graphene. my models: from django.db import models from mongoengine import * # Create your models here. class Product(Document): name = StringField(required=True) pCode = StringField(required=True) sku = StringField() cost = StringField() price = StringField() category = StringField() meta = { "indexes":["name","pCode"] } my schema: import graphene from graphene_django import DjangoObjectType from .models import Store, Vendor, Product class ProductType(DjangoObjectType): class Meta: model = Product fields = ("name","pCode","price") class Query(graphene.ObjectType): all_products = graphene.List(ProductType) def resolve_all_products(root, info): return Product.objects.all() schema = graphene.Schema(query=Query) It is almost as if the document class doesnt pass something correctly...please help -
Django How to get sum of column after doing subtraction on each row?
For example, I have an item where the "soldprice" price was 10, the "paid" was 2 and the "shipcost" was 2. I am currently doing as follows: @property def profit(self): if self.soldprice is not None and self.paid is not None and self.shipcost is not None: return self.soldprice - self.paid - self.shipcost And the return should be 6, (10 - 2 - 2). I am then calling that profit property in a template. {% for inventory in inventory %} <tr> <td><a class='btn btn-success btn-sm' href=''>View Breakdown</a> <td>{{inventory.id}}</td> <td>{{inventory.product}}</td> <td>{{inventory.description}}</td> <td>{{ inventory.profit }}</td> </tr> {% endfor %} So I see things as below: ID Product Profit ---------------------------------------- 6 dessert 8.80 7 bowls 3.37 8 bowls 16.32 15 chip 6.19 What is the best way to add the "Profit" column up after calling the profit property? So for example, the total for the above would be 34.68 so I can display that in the template. Any and all help is greatly appreciated. -
How to use a javascript variable inside a Django {% url %} tag?
Im trying to dynamically change the link of a button based on which div a user has currently selected. I tried to run a quick test with a JS variable in the HTML script tag, but Django isn't reading the variable like a num. <script type="text/javascript"> const testing = 10 </script> <a href="{% url 'battlefield:onevsone_trainer_selection' num_trainers=testing %}" class='description__button btn btn__large'>Next ></a> URL looks like: path('one-vs-one/trainers/<int:num_trainers>', views.oneVsOne, name='onevsone_trainer_selection') Not sure exactly why it's not working. When I passed it a string of '10' it worked -
django-filter search filed not able to recognize and filter the None value
I'm using django-filter: filter.py: import django_filters TYPE_CHOICES = (('One', 'One'), ('Two', 'Two'),(None,None)) class MyFilterSet(django_filters.FilterSet): Type = django_filters.ChoiceFilter(choices=TYPE_CHOICES) class Meta: model = Mymodel fields = ['Type '] In the UI form select filed, when I choice the None ,and submit ,the system can't find the None value one. Nothing happen. I have tried convert the None to sting None ,but it still not work. Any friend can help ? -
How to perform additional functions from a class UpdateViews
to edit my table I use UpdateViews , and pass there the same template as in the creation function: class CampaignEditor(UpdateView): model = Campaigns template_name = 'mailsinfo/add_campaign.html' form_class = CampaignsForm def get_context_data(self, **kwards): context = super().get_context_data(**kwards) data = list(Emails.objects.values()) # you may want to further filter for update purposes data = MailsTableWithoutPass(data) userID = self.object.user_guid all_mails = CampaignEmail.objects.values_list ('id','campaigne_guid', 'email_guid') context['data'] = editCampaignDataWork(data, userID, all_mails) return context def add_campaign(request): if request.method == 'POST': addCampaignDataToDB(request.POST) data = list(Emails.objects.values()) data = MailsTableWithoutPass(data) form = CampaignsForm() data_ = { 'form': form, 'data': data } return render(request, 'mailsinfo/add_campaign.html', data_) Saving the main form is fine, but apart from that my create function has extra steps, for one more database, it's all done in a function - addCampaignDataToDB : def addCampaignDataToDB(req): formCampaigns = CampaignsForm(req) IDs = req['IDs'] if IDs != '': IDs_list = IDs.split(',') user_guid = req['user_guid'][0] for i in IDs_list: CampaignEmail.objects.create(email_guid=int(i), campaigne_guid=int(user_guid)) if formCampaigns.is_valid(): formCampaigns.save() I encountered a problem that when calling a class for edit from a function addCampaignDataToDB only a fragment is executed: if formCampaigns.is_valid(): formCampaigns.save() But I need this whole feature to work As a result, I get that part of the actions are not executed and it seriously breaks my … -
Non model field in Django ModelSerializer
class Form(models.Model): key = models.UUIDField(unique=True, default=uuid.uuid4, editable=False) class Answer(models.Model): form = models.ForeignKey(Form, on_delete=models.CASCADE, related_name='answers') answer = models.TextField() class AnswerSerializer(serializers.ModelSerializer): form_key = serializers.UUIDField(write_only=True) class Meta: model = imported_models.Answer fields = ['id', "answer"] I want to create Answer based access on form_key. So i need to validate form_key as valid UUID key. How can i do that? -
Django. Filtering both related and relating model based on a field in relating one
I have two models: class Genre(models.Model): name=models.CharField() class Book(models.Model): name=models.CharField() genre=models.ForeignKey(Genre, related_name='book', on_delete=models.CASCADE) published=models.BooleanField() I also have basic serializers for them: class BookSerializer(serializers.ModelSerializer): class Meta: model=Book fields='__all__' class GenreSerializer(serializers.ModelSerializer): books = BookSerializer(source='book', many=True) class Meta: model=Genre fields='__all__' I need to query and serialize Genre models and related Book models excluding the books, which aren't published. I also don't need to query genres, which don't have published books. Example: g1=Genre(name='g1') #Serialize b1=Book(genre=g1, name='b1', published=False) #Don't serialize b2=Book(genre=g1, name='b2', published=True) #Don't serialize g2=Genre(name='g2') #Don't serialize, because there's no published books for this genre b3=Book(genre=g2, name='b3', published=False) #Don't serialize Desired result: [ { 'id': 1, 'name': 'g1', 'books': [ { 'id': 2, 'name': 'b2', 'published': true } ] } ] None of the filtering and excluding I tried worked. They all seem to affect only outer model (genre in this case) and I can't figure out how to filter underlying books first and then filter genres based on the result of book filtering. I found a workaround, but it involves multiple queries, creating new temporary genre and deleting it later, so this approach isn't really an option. -
upload_to and storage not working in Django 4.1
i have just upgrade my Django from 2.x to 4.x. I had a function that not working correctly. I have been trying so many things but still not able to figure it out. So i need some help file = models.FileField( upload_to=get_file_path, storage=AbsolutePathStorage(), max_length=500, ) from django.core.files.storage import FileSystemStorage class AbsolutePathStorage(FileSystemStorage): """Storage that allows storing files given absolute paths.""" def path(self, name: str) -> str: """Override path validation to allow absolute paths.""" # Return name if it's a absolute path. if name.startswith("/"): return name # Return regular joined path if this is a relative path. return super().path(name) So before upgrading Django, the file is uploaded to the upload_to folder ( outside of MEDIA_ROOT). Everything is working fine. But after i upgraded Django to 4.1. Its not working anymore and complaining about: The joined path (upload_to) is located outside of the base path component (MEDIA_ROOT ). Any idea ? Thank you.