Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Writable nested serializer method getting an Error while posting a request
models.py class Client(models.Model): client_id = models.AutoField(unique=True, primary_key=True) org = models.ForeignKey(Organisation, on_delete=models.CASCADE, related_name='org',null=True) product = models.ManyToManyField(Product,related_name='product') client_name = models.CharField(max_length=100) client_code = models.CharField(max_length=20) client_logo = models.ImageField(upload_to=upload_to,storage=DownloadableS3Boto3Storage, null=True, blank=True) currency = MoneyField(max_digits=10, decimal_places=2, default_currency='INR', null=True) billing_method = models.CharField(max_length=40) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email_id = models.EmailField(max_length=100) contact_no = models.CharField(max_length=20) mobile_no = models.CharField(max_length=20) description = models.TextField(max_length=500) street_address = models.CharField(max_length=250) city = models.CharField(max_length=50) state = models.CharField(max_length=50) country = models.CharField(max_length=50) pincode = models.CharField(max_length=10) industry = models.CharField(max_length=100) company_size = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_active = models.IntegerField(default=0, choices=STATUS_CHOICES) class Meta: db_table = "client_master" def __str__(self): return self.client_name serializers.py class Client_Serializers(serializers.ModelSerializer): #product_name = Product_Serializers(many=True) product = Product_Serializers(many=True) class Meta: model = Client fields = ('client_id','currency','billing_method','first_name','last_name','description','street_address','city','state','country','pincode','industry','company_size','client_name', 'contact_no','mobile_no', 'email_id','client_logo','client_code','product',) def create(self, validated_data): products_data = validated_data.pop('product') product = Product.objects.create(**validated_data) for product_data in products_data: Product.objects.create(product=product, **product_data) return product Data receiving on GET method { "client_id": 3, "currency": "0.05", "billing_method": "credit card", "first_name": "career", "last_name": "lab", "description": "NA", "street_address": "tiliconveli", "city": "tirunelveli", "state": "tamilnadu", "country": "India", "pincode": "600200", "industry": "software", "company_size": 100, "client_name": "techfetch", "contact_no": "1234567890", "mobile_no": "1234567890", "email_id": "icanio@gamil.com", "client_logo": "https://icanio-project-management.s3.amazonaws.com/client_logo/sup_bat_fDauRxK.jpg", "client_code": "TFH", "product": [ { "product_id": 5, "product_name": "time" } ] } But while posting it in the same format it is not getting posted, showing like { … -
Django REST Framework - Custom serializer overrides model constraints
My goal is to capitalize all letters coming in a specific field from the user payload in Django Rest Framework. Here the model: class Order(models.Model): class Item(models.TextChoices): FIRST= 'FIRST', _('FIRST') SECOND= 'SECOND', _('SECOND') ... order_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) the_item = models.CharField(max_length=8, choices=Item.choices) The only values admited are "FIRST" and "SECOND" in uppercase. I used this approach to capitalize the letters: In Django Rest Framework: from rest_framework import serializers class UpperCaseSerializerField(serializers.CharField): def __init__(self, *args, **kwargs): super(UpperCaseSerializerField, self).__init__(*args, **kwargs) def to_representation(self, value): value = super(UpperCaseSerializerField, self).to_representation(value) if value: return value.upper() and used in serializers.py like: class OrderCreateSerializer(serializers.ModelSerializer): #Force uppercase item = UpperCaseSerializerField() class Meta: model = Order fields = ['order_id', 'item' ] This actually works, because the input is converted in uppercase, BUT, the model constraints are not taken anymore into account. Payload Example 1: { "the_item": "first" } - LEGIT, converted in FIRST Payload Example 2: { "the_item": "FIRST" } - LEGIT, it's already uppercase Payload Example 3: { "the_item": "1234567" } - COMPLETELY WRONG INPUT, but it is accepted! It should be not! It's clear that it only cares about capitalizing and completely ignoring the model structure, which does not admit strings different from 'FIRST' and 'SECOND'. So, … -
'str' object has no attribute 'days'
when I add products to the vendor it shows this error 'str' object has no attribute 'days' class AddBaseproductToStore(AdminOnlyMixin, generic.TemplateView): template_name = 'manager-admin/add-product-to-store.html' def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) context['prod_id'] = self.kwargs['pk'] context['vendor'] = self.kwargs['vendor'] return context def get(self, request, *args, **kwargs): product = BaseProduct.objects.get(id=self.kwargs['pk']) vendor_id = self.kwargs['vendor'] base_cat = BaseCategory.objects.all() return render(request, self.template_name, {"product": product, "base_cat": base_cat, 'vendor': vendor_id}) def post(self, request, *args, **kwargs): base_product = BaseProduct.objects.get(id=self.kwargs['pk']) vendor_id = self.kwargs['vendor'] base_category = BaseCategory.objects.get(id=request.POST.get('category')) try: p = Product.objects.get(base_product=base_product, category=Category.objects.get(vendor_id=vendor_id, base_category=base_category)) except: product = Product() product.category = Category.objects.get(vendor_id=vendor_id, base_category=base_category) product.base_product = base_product product.name = request.POST.get('name') product.ar_name = request.POST.get('ar_name') product.sort_order = request.POST.get('sort-order') product.dryclean = request.POST.get('dryclean', '') == 'on' product.normal_dryclean_price = request.POST.get('dryclean_price') product.normal_dryclean_buffer_time = request.POST.get('dryclean_buffer') product.wash_and_pressing = request.POST.get('wash-press', '') == 'on' product.normal_wash_and_pressing_price = request.POST.get('wash-press-price') product.normal_wash_and_pressing_buffer_time = request.POST.get('wash-press-buffer') product.pressing = request.POST.get('press', '') == 'on' product.normal_pressing_price = request.POST.get('press-price') product.normal_pressing_buffer_time = request.POST.get('press-buffer') product.express_dryclean = request.POST.get('exp-dryclean', '') == 'on' product.express_dryclean_price = request.POST.get('exp-dryclean-price') product.express_dryclean_buffer_time = request.POST.get('exp-dryclean-buffer') product.express_wash_and_pressing = request.POST.get('exp-wash-press', '') == 'on' product.express_wash_and_pressing_price = request.POST.get('exp-wash-press-price') product.express_wash_and_pressing_buffer_time = request.POST.get('exp-wash-press-buffer') product.express_pressing = request.POST.get('exp-press', '') == 'on' product.express_pressing_price = request.POST.get('exp-press-price') product.express_pressing_buffer_time = request.POST.get('exp-press-buffer') product.save() if product.express_pressing == True or product.express_dryclean == True or product.express_wash_and_pressing_price == True: product.express = True else: product.express … -
Django returns 500 instead of 401 / 403 when no token passed
I have a Django view that requires a user to be authenticated (The app uses jwt), When the request is being passed without any Authorization header the response is 500, I want it to be 401 / 403 because it should not return an internal server error but an unauthorized error. I searched a lot and could not find a way to customize this behavior Here is the code: views.py: class GetProfileAPIView(APIView): permissions_classes = [permissions.IsAuthenticated] def get(self, request): user = self.request.user user_profile = Profile.objects.get(user=user) serializer = ProfileSerializer(user_profile, context={"request": request}) return Response(serializer.data, status=status.HTTP_200_OK) settings: DJOSER = { "LOGIN_FIELD": "email", "USER_CREATE_PASSWORD_RETYPE": True, "USERNAME_CHANGED_EMAIL_CONFIRMATION": True, "PASSWORD_CHANGED_EMAIL_CONFIRMATION": True, "SEND_CONFIRMATION_EMAIL": True, "PASSWORD_RESET_CONFIRM_URL": "password/reset/confirm/{uid}/{token}", "SET_PASSWORD_RETYPE": True, "PASSWORD_RESET_CONFIRM_RETYPE": True, "USERNAME_RESET_CONFIRM_URL": "email/reset/confirm/{uid}/{token}", "ACTIVATION_URL": "activate/{uid}/{token}", "SEND_ACTIVATION_EMAIL": True, "SERIALIZERS": { "user_create": "apps.users.serializers.CreateUserSerializer,", "user": "apps.users.serializers.UserSerializer", "current_user": "apps.users.serializers.UserSerializer", "user_delete": "djoser.serializers.UserDeleteSerializer", }, } REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", ) } SIMPLE_JWT = { "AUTH_HEADER_TYPES": ( "Bearer", "JWT", ), "ACCESS_TOKEN_LIFETIME": timedelta(minutes=120), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), "SIGNING_KEY": "supersecretkey~!", "AUTH_HEADER_NAME": "HTTP_AUTHORIZATION", "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",), } enter code here -
whitespace data when deleting in django
I'm planning to delete comments just like in any other social media apps. The problem is when I do .delete() function. it only removes the strings but not the row itself, making it only whitespaces. delete function def delete_comment(request): formType = request.POST.get('formType','') postID = request.POST.get('postID','') commentID = request.POST.get('commentID','') deleteComment = Comment.objects.get(id = commentID).cleanData() result = { 'code': 0, } return JsonResponse({'result':result}) EventListener in $('.delete-button').on('click', function(e){ e.preventDefault(); var commentID = $(this).attr('comment-id'); var form_type = $(this).attr('form-type'); var postID = $(this).attr('post-id'); $.ajax({ type: "POST", url: '/api/comment/edit_comment', data: { "formType":form_type, "postID":postID, "commentID":commentID, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success: function(data) { $('.commentCard-'+ commentID).remove(); }, cache: false }); }); html <form action ="" form-type="deletebtn"> <button type="button" class="delete-button post-options btn text-nowrap" post-id = {{ post.id }} comment-id = {{Post_comment.id}} on-click="remove_comment({{post.id}}, {{Post_comment.id}})" > <i class='bx bx-message-square-x'></i> </button> </form> result when deleting result -
Filtering Base Django User by multiple groups
In my Django project I'm using base Django User and Group models. My goal is to get User queryset containing all User object who are assigned to multiple groups at the same time. For example I two groups and three users: from django.contrib.auth.models import User, Group a = Group.objects.create(name='a') b = Group.objects.create(name='b') user_a = User.objects.create_user('a', 'a@a.com', 'a') user_a.groups.add(a) user_b = User.objects.create_user('b', 'b@b.com', 'b') user_b.groups.add(b) user_ab = User.objects.create_user('ab', 'ab@ab.com', 'ab') user_ab.groups.add(a) user_ab.groups.add(b) I have tried filtering using __in on groups nad Q, but with no effect from django.db.models import Q User.objects.filter(groups__in=[a,b]).distinct() <QuerySet [<User: a>, <User: ab>, <User: b>]> User.objects.filter(Q(groups=a) & Q(groups=b)) <QuerySet []> My expected result would be: User.objects.filter(???) <QuerySet [<User: ab>]> -
Django & Ajax chat application
in this chat application i made a room page and i am trying to get messages to this room as jsonResponse but i keep getting this error 'method' object is not iterable... the view: def room(request,room): username = request.GET.get('username') room_details = Room.objects.get(name=room) messages = Message.objects.filter(room=room_details.id) return render(request,'room.html',{ 'username': username, 'room': room, 'room_details': room_details, }),JsonResponse({'messages':list(messages.values)}) Scripts: * $(document).ready(function(){ setInterval(function(){ $.ajax({ method: 'GET', url : "", success: function(response){ console.log(response); $("#display").empty(); for (var key in response.messages) { var temp="<div class='container darker'><b>"+response.messages[key].user+"</b><p>"+response.messages[key].value+"</p><span class='time-left'>"+response.messages[key].date+"</span></div>"; $("#display").append(temp); } }, error: function(response){ alert('An error occured') }, complete: function(xhr,status){ console.log(status); console.log(xhr); } }); },1000); }) </script>* -
Get value from many to many relation django
I would like to get value of the field 'name' of the model User but facing some issues. accounts = list(Account.objects.all()) To receive some value from foreign key models I use: accounts.currency.code (where Account my main model, Currency foreign key model and Code is required field) But for model with manytomany relation this way doesn't work. accounts.user.name 'ManyRelatedManager' object has no attribute 'name' But there name is a charfield of the model User. -
Prevent need for the same select_related clause on multiple views in DRF
Given the following models... class Player(models.Model): user = models.ForeignKey(User) class Activity(models.Model): player = models.ForeignKey(Player) and these serializers... class PlayerSerializer(serializers.ModelSerializer): class Meta: model = Player fields = ['user'] class ActivitySerializer(serializers.ModelSerializer): player = PlayerSerializer() class Meta: model = Activity fields = ['player'] if I want to use django-rest-framework to list all the activities, I need to do something like this... class ActivityViewSet(viewsets.ReadOnlyModelViewSet): queryset = Activity.objects.select_related("player__user") <--- this is needed because the activity serializer is going to serialize the player which has a user serializer_class = ActivitySerializer That's all fine. But then, every time I write a new view which, at some level, uses PlayerSerializer, I'm going to have to remember to do the proper select_related clause in order to keep the number of DB lookups low. I'm going to end up writing a lot of views which have the same select_related clauses (mine are actually a LOT more complicated than this example) and, if the PlayerSerializer ever changes, I'm going to need to remember to change all the view lookups. This doesn't seem very DRY to me and I feel like there must be a better way to do it. Have I missed something obvious? -
How to serch using queryset on Django
I have Topic model and Post model. I want to search using queryset. When q has string it work well, however when q = '' (which means All ) it doesn't show all post. How can I fix this? All code here models.py class Topic(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User,on_delete=models.CASCADE) topic = models.ForeignKey(Topic,on_delete=models.SET_NULL,null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail',kwargs={'pk':self.pk}) views.py class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 def get_context_data(self, **kwargs): context = super(PostListView, self).get_context_data(**kwargs) context["topics"] = Topic.objects.all() return context def get_queryset(self): if self.request.GET.get('q') != None: q = self.request.GET.get('q') else: q = '' # q = self.request.GET.get('q') if self.request.GET.get('q') != None else '' return Post.objects.filter(topic__name__icontains=q).order_by('-date_posted') -
What is the most successful short-code in Django for creating a sign-in + register + email verification?
What is the best shortcode in Django for creating a sign-in + register + email verification? -
django context not rendering in html
Hi I have 'easy' problem with context in django ;/ I try to send context to render and show it in html page but it dosen't showing. urls path('', views.home, name='home'), path('viki/main', views.vikimain, name='vikimain'), views @login_required(login_url='login') def home(request): return render(request, 'project/home.html') @login_required(login_url='login') def vikimain(request): dict = {'test': 'test'} return render(request, 'project/main.html', dict) main.html {% extends 'project/base.html' %} {% block content %} <div>{{ dict }}</div> {% endblock %} -
How to improve performance of Django ORM already querying with prefetch_related? (many different tables involved)
I have a Django model which is linked by many other models in a reverse ForeignKey relationship, that is many-to-one. Illustration: class ModelA: photo_url = URLField(null=True) class AbstractModel: class Meta: abstract = True modelA_ref = ForeignKey(to=ModelA, on_delete=dj_models.CASCADE) class ModelB(AbstractModel): whatever = TextField(null=True) class ModelC(AbstractModel): whatever = TextField(null=True) class ModelD(AbstractModel): whatever = TextField(null=True) and so on for a dozen more. I have a serializer for ModelA, and a corresponding view for when I call the corresponding endpoint /api/v1/modela/<uuid:key>/ in Django REST Framework. Illustration: from rest_framework.generics import RetrieveAPIView class ModelASerializer: modelb_field = ListSerializer(source="modelb_set", child=ModelBSerializer()) modelc_field = ListSerializer(source="modelc_set", child=ModelCSerializer()) modeld_field = ListSerializer(source="modeld_set", child=ModelDSerializer()) class ModelAView(RetrieveAPIView): serializer_class = ModelASerializer lookup_field = "id" lookup_url_kwarg = "key" def get_queryset(self): key = self.kwargs["key"] return ModelA.objects.filter(id=key).prefetch_related( 'modelb_set', 'modelc_set', 'modeld_set' ) Of course, this optimization does not prevent Django from querying all the different tables when the /api/v1/modela/<uuid:key>/ endpoint is reached, as expected: in my situation, the accumulation of queries takes 60% of the 1000ms response time, which is way too long. Hence my question: is refactoring my database schema to make those models fit into one single table my only option? or is there something more elegant to be done? Thank you for your time. -
in django how can i access the tables of my sql database created with xampp
i have installed mysqlclient in my project virtual environment and also changed the setting.py in order to connect to mysql database(which is with xampp). image and then i have run the "python manage.py migrate" command. and now all looks okay. image so now i want to know how can i access the tables to retrieve data or to change(update, insert) through django. for example with django orm you have models of your database that can be used. but what can i do here? any ideas can help. ps: sorry for the way of telling the problem. i'm not english(and also i'm new to django). -
Django Query with and without comma
I have a .csv file with only one column (name) and multiple rows containing strings formatted like: "name, surname" "name surname" I loop through this file and check if they exist in my database the only problem is that in my database, everything is formatted like: "name, surname" so the query without a comma could not be found unless I do something like this: Model.objects.filter(name__search=row["name"]) But this takes a very long time to load.. is there any other way? -
NGINX GUNICORN FOR DJANGO APPLICATION COMPLETE SETUP ON DISTRIBUTED SYSYTEM [closed]
I HAVE ONE WEBSERVER WHICH IP IS XX.XX.XX.59 AND HAVE ANOTHER APPLICATION SERVER ON XX.XX.XX.27 I WANT T -
how to show show db. data for all template using base template
hello I m new in Django I m creating a Django ecommerce project nd I created I slider in base template I want to show slider in all the template ..first template its working properly but if I go for some other template like section then its not showing images nd product name which I extends from base template ..hope some one help us . base.html <div class="container bg"> <div id="demo" class="carousel slide my-3" data-ride="carousel"> <ul class="carousel-indicators"> <li data-target="#demo" data-slide-to="0" class="active"></li> <li data-target="#demo" data-slide-to="1"></li> <li data-target="#demo" data-slide-to="2"></li> </ul> <div class=" carousel-inner "> <div class="carousel-item active"> <div class="row"> <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card" style="width: 18rem;"> <img src="/media/{{cake.0.images}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{cake.0.prodname|title}}</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card" style="width: 18rem;"> <img src="/media/{{cake.1.images}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{cake.1.prodname|title}}</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card" style="width: 18rem;"> <img src="/media/{{ic.0.images}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 … -
Django Deploy ElasticBeanstalk StaticFiles(JS/CSS) not loading
My Styles Are Not Loading: settings.py: STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'static' STATICFILES_DIRS = [BASE_DIR / 'templates/static'] MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' error eb logs: Apr 26 06:11:06 ip-172-31-46-75 web: Not Found: /static/assets/bootstrap/css/animate.css Apr 26 06:11:06 ip-172-31-46-75 web: Not Found: /static/assets/bootstrap/css/flex-slider.min.css Apr 26 06:11:06 ip-172-31-46-75 web: Not Found: /static/assets/bootstrap/css/slicknav.min.css Apr 26 06:11:06 ip-172-31-46-75 web: Not Found: /static/assets/custom/css/style.css ETC.......... I also did in my env python manage.py collectstatic and eb deploy , it still didnt load my css/js(html is perfectly loading) my .ebextensions: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: store.wsgi:application -
my Django form is showing an error when i tried creating an user object
In my Sign up form I tried to create an object called myuser from Django.contrib.auth.models this is the image It's showing an error from django.contrib.auth.models import User def signup(request): if request.method == "POST": fname = request.POST['fname'] lname = request.POST['lname'] email = request.POST['email'] pass1 = request.POST['pass1'] pass2 = request.POST['pass2'] myuser = User.objects.create_user( fname , email , pass1) myuser.first_name = fname myuser.last_name = lname context = {} return render(request, '/Users/tanajkhanuja/Desktop/bee/main/templates/main/Signup.html', context) -
django 4.0.4 ./manage working, however when using the management command 'runserver', an error is returned
A peculiar thing is happening with my Django Manage script. No changes have been made since yesterday, however 'runserver' stopped working, and returns: ValueError: illegal environment variable name If I run other management functions that script works fine, so I get no errors, unless I use the 'runserver' If I run ./manage on it's own, I get the management command list: Type 'manage.py help ' for help on a specific subcommand. Available subcommands: [auth] changepassword createsuperuser [contenttypes] remove_stale_contenttypes [django] check compilemessages createcachetable dbshell diffsettings dumpdata flush inspectdb loaddata makemessages makemigrations migrate sendtestemail shell showmigrations sqlflush sqlmigrate sqlsequencereset squashmigrations startapp startproject test testserver [sessions] clearsessions [staticfiles] collectstatic findstatic runserver -
authenticate django using oAuth2 for integration with elasticsearch
I have worked on a django app with elasticsearch as backend. During development I have used a local elasticsearch instance running in docker and connected to it using username and password as below. Now I need to change authentication to Oauth2 using azure AD. Cant find any good documentation on how to do it. from django settings.py: user_name = "elastic" host_ip = "127.0.0.1" host_ports = 9200 elk_url = f'https://{user_name}:{ESPASSWORD}@{host_ip}:{host_ports}' ELASTICSEARCH_DSL = { 'default': { 'hosts': elk_url, 'ca_certs': False, 'verify_certs': False, } } Help is appreciated -
How to send pictures from React-Native app to the Django server using Expo ImagePicker?
I study React Native and Django and create an iOS app, which recognize text in pictures. I need to upload images to the Django Server but I have error from server: [26/Apr/2022 12:10:51] "POST /api/textocr/ HTTP/1.1" 400 519 error {'title': [ErrorDetail(string='Обязательное поле.', code='required')], 'image': [ErrorDetail(string='Расширение файлов “” не поддерживается. Разрешенные расширения: bmp, dib, gif , tif, tiff, jfif, jpe, jpg, jpeg, pbm, pgm, ppm, pnm, png, apng, blp, bufr, cur, pcx, dcx, dds, ps, eps, fit, fits, fli, flc, ftc, ftu, gbr, grib, h5, hdf, jp2, j2k, jpc, jpf, jpx, j2 c, icns, ico, im, iim, mpg, mpeg, mpo, msp, palm, pcd, pdf, pxr, psd, bw, rgb, rgba, sgi, ras, tga, icb, vda, vst, webp, wmf, emf, xbm, xpm.', code='invalid_extension')]} Bad Request: /api/textocr/ What I did: Django Server: models.py from django.db import models # Create your models here. class Ocr(models.Model): title = models.CharField(max_length=100, blank=False, null=False) image = models.ImageField(upload_to='images/', null=True, blank=True) def __str__(self): return self.title serializers.py: from rest_framework import serializers from .models import Ocr class PostSerializer(serializers.ModelSerializer): class Meta: model = Ocr fields = '__all__' views.py: from django.shortcuts import render from .serializers import PostSerializer from .models import Ocr from rest_framework.views import APIView from rest_framework.parsers import MultiPartParser, FormParser from rest_framework.response import Response from … -
How can I do a query with multiple distinct Q objects?
I have a preference model in my Django app, and I am trying to write a query that filters to items that have two preferences set in a certain way. The preferences are stored many-to-many, so each object has multiple preferences linked to it. For preference 1, I can check with: Team.objects.filter(teampreferencemodel__name='remind_morning', teampreferencemodel__raw_value='a') For preference 2, I can check with: Team.objects.filter(teampreferencemodel__name='remind_days_before', teampreferencemodel__raw_value='5') My goal is to get the intersection of those two queries. I thought I could do something like: Team.objects.filter(Q(teampreferencemodel__name='remind_morning', teampreferencemodel__raw_value='a')), Q(teampreferencemodel__name='remind_days_before', teampreferencemodel__raw_value='5')) but it appears (I think) that Django is trying to satisfy both Qs with the same teampreferencemodel, rather than finding one that has one of each. Is there any way to optimize this query, via Q or something else, or do I need to just resort to: Team.objects.filter(teampreferencemodel__name='remind_morning', teampreferencemodel__raw_value='a').intersection( Team.objects.filter(teampreferencemodel__name='remind_days_before', teampreferencemodel__raw_value='5')) or slightly better: Team.objects.filter(teampreferencemodel__name='remind_morning', teampreferencemodel__raw_value='a').filter( teampreferencemodel__name='remind_days_before', teampreferencemodel__raw_value='5')) It just feels like there should be a better way... -
Sharing models between two Dockerizable Django projects and ForeignKey to a model
I want to create three Django projects. The projects sharing models between them on the same database like modular monolith structure. How Can I access a model from the other project for ForeignKey to a model. I've been doing research and application on the subject, but I still haven't found how to set up a structure. -
Submitting SUMMARY Data from Django to React using DRF
I'm starting to test some API data between django and React using Rest API. I'm able to submit this data between Djnago model and React front end. [ { "id": 1, "gender": "Male", "age": 40, "updated": "2022-04-25T18:55:23.304456Z", "created": "2022-04-25T14:07:48.282139Z" }, { "id": 2, "gender": "Male", "age": 33, "updated": "2022-04-25T18:55:23.304456Z", "created": "2022-04-25T14:07:48.282139Z" }, { "id": 3, "gender": "Female", "age": 22, "updated": "2022-04-25T18:55:23.304456Z", "created": "2022-04-25T14:07:48.282139Z" }, { "id": 4, "gender": "Female", "age": 33, "updated": "2022-04-25T18:55:23.304456Z", "created": "2022-04-25T14:07:48.282139Z" }, ] My goal is not to submit this raw data, but instead to submit summary data (data analysis) that calculates the average age for males and females, so I should be getting something like this: [ { "gender": "Male", "average_age": 36.5, }, { "gender": "Male", "average_age": 27.5, } ] Where should I be making these cross tabulations? on the backend or front end? if on the backend should I be creating new models for the summary data? I tried looking online for advice on this but I was unlucky!