Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM - How to optimize query for aggregating SUM from different models?
I need to fetch data which contains the total earnings of users within a given date range (from_date and end_date). For example, given from_date=2020-01-01 and end_date=2020-01-07, user 'A' user has a total earnings of 1,000 on 2020-01-01, and then user 'A' has a total earnings of 20,000 on 2020-01-07, the output should be 19,000 since 20000 - 1000 = 19000. In my system, a User model is foreign key with Account model, and a user can have multiple accounts. An AccountModel is foreign key (one is to one) with AccountBonus model, which contains different bonuses that needs to be aggregated in order calculate the total earnings of each user. AccountBonus model inherits the package django-simple-history (https://django-simple-history.readthedocs.io/en/latest/), which creates a new row of data whenever AccountBonus is updated with datetime. Another model is foreign key with Account model which also needs to be aggregated for the total earnings which is AdsCommission model. This is what I'm currently using as a query for this, but it seems like it is too slow even if I have paginator class LIMIT and OFFSET implemented. How can I optimize this query further more? users = User.objects.exclude(groups__name__in=[UserGroups.Admin]) earnings_start = Subquery(AccountBonus.history.filter( Q(history_date__date__gte=from_date) & Q(account__user__pk=OuterRef('id')) ).order_by("history_date")[:1].annotate( total_earnings=Sum(F('itoken_plus_bonus') + … -
Merge two Querysets in django that get annotated
I have a model "Shift" for guards schedule program I do annotation on two django queryset to create status column for night and day shifts night_shift=Shift.objects.filter(nightـguard__guards__pk=self.request.user.pk).annotate(status=Value("night", output_field=CharField())) day_shift=Shift.objects.filter(dayـguard__guards__pk=self.request.user.pk).annotate(status=Value("day", output_field=CharField())) but when i merge this two queryset with code below my_shift=(day_shift | night_shift).distinct() The annotation field "status" that i create did not work very well and all status get to "day" what is the solotion ? -
Django - Check if file entry exists at one of X tables
I need to check if a file field is given at one of 5 different models, how can I do that (preferably in one statement)? file = models.CharField(verbose_name=_("Filename Descriptor"), blank=False, null=False, editable=False, max_length=255, unique=True) So basically I want to check if the file already exists in one of these 5 models/tables Thanks in advance -
How to pass the value of console.log to django views?
I have seen so many responses but none of those correspond to my needs. Basically I am trying to get the value of an href through JavaScript and I need to pass that to my django views, when I do a console.log this is the output that I am getting http://localhost:8000/#vert-tabs-Personal localhost:8000:316:21 #vert-tabs-Personal localhost:8000:317:21 http://localhost:8000/#vert-tabs-Career localhost:8000:316:21 #vert-tabs-Career localhost:8000:317:21 http://localhost:8000/#vert-tabs-Finances localhost:8000:316:21 #vert-tabs-Finances And here is the script that triggered the output so far <script> $(".nav-link").on('click', function(e){ console.log(e.target.href); console.log(e.target.hash); }); </script> Now What is the best way to get the e.target.hash value passed to my django views. I am thinking of jquery or ajax but honestly I don't know. Any help would be appreciated. Thank you in advanced... -
Raw query not returning any results using Django MySQL
I'm trying to run a query in Django. For this project, I use two different connectors: MariaDB and Django's MySQL default connector In the local server, I use the MariaDB connector (everything works fine) and in the staging server, I use MySQL (everything works ok except this query). I guess that the error will be in the syntax, but checking the official Django documentation I have not seen anything unusual. MariaDB -> Works ok and returns results. MySQL -> Does not return any results (the database is the same for both local and staging servers, same content, same table, exactly identical copies of each other). MySQL (not returning any results): from django.db import connection def get_data(variant): results = [] cursor = connection.cursor() cursor.execute("SELECT b.spec_id, b.h_loss, c.gen_type FROM `db-dummy`.spec_gen_data c JOIN `db-dummy`.gen_info a ON a.record_id = c.gen_id JOIN `db-dummy`.spec_data b ON b.record_id = c.spec_id WHERE b.h_loss = 1 AND (a.ref_gen = %s OR a.detail_ref_gen = %s) AND c.gen_type BETWEEN 1 AND 5 ORDER BY a.gen_name;", ('{}%'.format(variant),'{}%'.format(variant),)) columns = [column[0] for column in cursor.description] results = [] for row in cursor.fetchall(): results.append(dict(zip(columns, row))) return results MariaDB (working): import mariadb def get_data(variant): results = [] conn = mariadb.connect( user="user", password="password", host="localhost", database="db-dummy") cursor … -
Can I access others MySQL database in Python Django without having access to its models?
I have this connection to MySQL Workbench database. The thing is, the database and tables isn't made by my django project so I don't have any access to its class models. Is there any way I can add, update or delete in the database tables? tables: TestTable1, TestTable2, TestTable3 `` DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'test', 'USER': 'root', 'PASSWORD': '1234', 'PORT': 3306, 'HOST': '127.0.0.1', 'OPTIONS': { 'charset': 'utf8mb4', 'use_unicode': True, }, } } `` -
Django TimeField Widget change on admin panel
I'm working with models.TimeField model which will be shown in admin panel and django time fields is uncomfortable. It offers Now, Midnight, Noon keywords. how can i change that, how can i change them to detailed timedeltas? Like this -
Getting an Aggregate Value from a Many-to-Many Field inside a Serializer
We have an API endpoint that generates a response. However, we would like to aggregate some of the data and add an additional field to the serializer. { "id": 61, "not_owned_value": # This is what we're trying to get (Aggregate best_buy_price from not_owned_inventory PlayerProfiles) "not_owned_inventory": [ # PlayerProfile objects "29666196ed6900f07fc4f4af4738bffe", "0ff73ca20cd787c5b817aff62e7890da", "99d4eaef9991695d7ad94b83ad5c5223", "6fcabe9f9c8a95980923530e7d7353a7", "80b34c84a6e5ed25df112c11de676adc", "0a4c5b96474f0584519d1abc4364d5a2", "9ed1f55ac4f3b402b1d08b26870c34a6", ] } Here is the models.py class PlayerProfile(models.Model): card_id = models.CharField(max_length=120, unique=True, primary_key=True) name = models.CharField(max_length=120, null=True) class PlayerListing(models.Model): player_profile = models.OneToOneField( PlayerProfile, on_delete=models.CASCADE, null=True) best_buy_price = models.IntegerField(null=True) class InventoryLiveCollection(models.Model): not_owned_inventory = models.ManyToManyField(PlayerProfile, related_name="not_owned_inventory") Here is the serializer.py class InventoryLiveCollectionSerializer(serializers.ModelSerializer): not_owned_inventory = PlayerProfileAndListingForNesting(read_only=True, many=True) class Meta: model = InventoryLiveCollection fields = ( 'id', 'date', 'not_owned_value', # Trying to get this 'not_owned_inventory', ) How can I aggregate the best_buy_price of the player_profile objects that belong to a specific InventoryLiveCollection__not_owned_inventory? -
Not getting correct PRIMARY KEY
After going to the profile link: http://127.0.0.1:8000/basic_app/profile/3/ Then trying the link: http://127.0.0.1:8000/basic_app/profile/2/ It is working. So there must be some issue with primary key. And I figured out that this is happening after creating a superuser. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. BLOOD_CHOICES = ( ('o+', 'O+'), ('o-', 'O-'), ('a+', 'A+'), ('a-', 'A-'), ('b+', 'B+'), ('b-', 'B-'), ('ab+', 'AB+'), ('ab-', 'AB-'), ) class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # additional last_date = models.DateField(blank=False) contact_no = models.CharField(max_length=15, blank=True, null=True) blood_group = models.CharField( max_length=4, choices=BLOOD_CHOICES, default='o+') def __str__(self): return self.user.username forms.py from django import forms from django.contrib.auth.models import User from .models import UserProfileInfo class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ('first_name', 'last_name', 'username', 'email', 'password') widgets = { 'first_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder':'First Name'}), 'last_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Last Name'}), 'username': forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Choose an Username'}), 'email': forms.EmailInput(attrs={'class': 'form-control', 'placeholder':'Your Email'}), 'password': forms.PasswordInput(attrs={'class': 'form-control', 'placeholder':'Your Password'}) } class UserProfileInfoForm(forms.ModelForm): class Meta(): model = UserProfileInfo fields = ('contact_no', 'blood_group', 'last_date') widgets = { 'contact_no': forms.NumberInput(attrs={'class': 'form-control', 'placeholder':'Your Personal Phone Number'}), 'blood_group': forms.Select(attrs={'class': 'form-control', 'placeholder':'Your Blood Group'}), 'last_date': forms.DateInput(attrs={'class': 'form-control', 'placeholder':'The last date you donated blood'}), } basic_app/urls from django.urls import path from … -
How to implement multiple filters Django?
I want to add such filters to my internet shop: Color: red blue green Material: plastic wood metal where each of points is a checkbox, color and material are fields of some Django model. For example if i'm looking for red or blue toys with plastic material, i'll find it in such way: filtered = SomeModel.objects.filter(material=plastic, color=red, color=blue) But how to filter it dynamically?(if i have many filters) -
Python application on server [closed]
I have a question: I work mostly with java and with servers such as jboss or weblogic and now I would need some advice on which server would be optimal for building an application with python. Which server is the best and why? Thank you in advance. -
How to trigger Django signals only once on multiple receivers
I am looking for a way to do the following (keep in mind, if this is not possible with signals, I'm happy if you know any alternatives) But let's say we have a signal defined as follows: from django.dispatch import receiver @receiver(post_save, sender=Model1) @receiver(post_save, sender=Model2) @receiver(post_save, sender=Model3) def my_signal_handle(sender , **kwargs) # some code here Now, all 3 models (Model1, Model2, Model3) are related. So when creating a new resource, one can provide all informations, which results in all 3 tables being saved with a new row. I would love to only trigger my_signal_handle once in that case. So basically per transaction. Also, when updating for example, one could only update, let's say Model3, and in that case I still want this signal to run. So goal is -> No matter how many models are affected, I want to run this signal once. Hope it makes sense, happy to clarify better if needed. I was looking at adding a signal per transaction or something, but couldn't find exactly what I need. -
how to use drf-yasg to import a swagger.yml file?
I tried django-swagger-ui but not work python 3.9.5 django 3.2.3 drf-yasg 1.20.0 -
Problem with Google OAuth and Django: "Credentials in post body and basic Authorization header do not match"
I tried to arrange auth via Google in my Django app following this guide (there other identical examples over the internet). It didn't work and I tried to debug as suggested here. That gave me error as follows: {'provider_id': 'google', 'error': 'unknown', 'exception': 'Error retrieving access token: b\'{\\n "error": "invalid_request",\\n "error_description": "Credentials in post body and basic Authorization header do not match"\\n}\'', 'extra_context': {}} I have a feeling that this is somehow related to the fact that before I used default auth that comes with Django with this app. Any clue to further debug would be appreciated. -
Python Django API task
I need help to build API using django and DRF. API for an online bookstore with the ability to place an order for registered users. An hour after order completed send 'Thanks for purchase' email to that user -
Django validating time slot
This is my models to store availability of particular time when a new booking there class TimeSlot(models.Model): day = models.ForeignKey( Day, on_delete=models.CASCADE, related_name="time" ) booking = models.ForeignKey( Booking, on_delete=models.CASCADE, related_name="time" ) start_hour = models.TimeField() end_hour = models.TimeField() class Meta: unique_together = [('end_hour', 'start_hour',)] def clean(self): pass Currently it's allowing booking even those are considered as duplicate in terms of end_hour and start_hour. I want to prevent the slot, so that no new booking shouln't placed between a range that already booked. Can anyone know how to do it with the range? -
How to get the domain name of my React frontend which is making a request to my Django backend?
I want Django to print the domain name of the React frontend which is making a request to my Django server. get_current_site gives the domain name of the Django server. So how can I get the domain name of the site, making a request to the Django server? -
find out how api authenticate users Django
I am working with a MySQL database managed by a django app and an api on which I do not have access. I will find out later how the api works but I need to make this functionality now for a presentation. The passwords in the database are stored this way $2a$10$rA59QU2GsWR4v6hugdYhruxY0bgZYVLv6ncxRe3BiDJMEpK0A0huW - when user registers from the legacy app. From my django app, users register and passwords are stored this way $2b$12$koykshnEpT39MgciBp4FGepw.LnbHt2Kmqbfm4TSipX6FAVRVKdjW. Django app can authenticate and passwords are validated ok no matter how many iterations are there and prefix $2b$ or $2a$. But recently in order to access an api feature I've needed to log in the user from the api side, so if I authenticate user using dajngo's generated password hash, the api does not succeed to authenticate. The question is, What do I need to tackle in order to make it work? I have tried to change iterations from 12 to 10, did not work. Now I want to change the prefix to 2a, not sure if it will work but anyway. Next I found that the password can be hashed with or without null terminator -> correct me if Im wrong but I need to … -
How to transfer data from old database to new modified database in django?
I have old django project and new django project. I created dump file from database of old django. And also I made changes in tables and created new tables. Now I want to load that dump file to my new django app. I am facing errors when I firstly migrate then restore data or firstly restore then migrate.. When I do migration first, it says tables already exist. When I do restore first , it says django.db.utils.ProgrammingError: relation "django_content_type" already exists I use migrate --fake error goes but new tables are not created in database. I spent 3-4 days but could not succeed. Please, help me if you can. PS: my database is postgresql -
Django migrations error: dont create authomatically permissions and contenttypes
I work with django 1.8.7 and python 2.7 . I have peoblem with migrate. when I migrate my models , permission and contenttypes don't create automatically. error looks like this: Traceback (most recent call last): File "/home/mariocesar/Proyectos/Crowddeals/env/local/lib/python2.7/site- packages/django/core/management/base.py", line 222, in run_from_argv self.execute(*args, **options.__dict__) File "/home/mariocesar/Proyectos/Crowddeals/env/local/lib/python2.7/site- packages/django/core/management/base.py", line 252, in execute output = self.handle(*args, **options) File"/home/mariocesar/Proyectos/Crowddeals/crowddeals/core/management/commands/update_pe rmissions.py", line 29, in handle create_permissions(app, get_models(), options.get('verbosity', 0)) File "/home/mariocesar/Proyectos/Crowddeals/env/local/lib/python2.7/site- packages/django/contrib/auth/management/__init__.py", line 74, in create_permissions for perm in _get_all_permissions(klass._meta, ctype): File "/home/mariocesar/Proyectos/Crowddeals/env/local/lib/python2.7/site- packages/django/contrib/auth/management/__init__.py", line 28, in _get_all_permissions _check_permission_clashing(custom, builtin, ctype) File "/home/mariocesar/Proyectos/Crowddeals/env/local/lib/python2.7/site- packages/django/contrib/auth/management/__init__.py", line 49, in _check_permission_clashing for codename, _name in custom: ValueError: too many values to unpack and when I change migrations file like this: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.auth.management import _get_builtin_permissions, _check_permission_clashing from django.db import migrations, models from django.conf import settings def _get_all_permissions(opts, ctype): """ Returns (codename, name) for all permissions in the given opts. """ builtin = _get_builtin_permissions(opts) custom = list(opts.permissions) if any(isinstance(el, basestring) for el in custom): custom = [custom] _check_permission_clashing(custom, builtin, ctype) return builtin + custom class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='JsonModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('data', models.CharField(max_length=1000000)), ('generatedtime', models.DateTimeField(auto_now_add=True, null=True)), ('title', models.CharField(max_length=200, null=True, … -
Failed to load resource: though the file is placed there
I am using python,To display image to a page,i am getting the below errors GET http://127.0.0.1:8000/static/neo4j/avatar1.png 404 (Not Found) 127.0.0.1/:30 GET http://127.0.0.1:8000/static/neo4j/logo-png-type.png 404 (Not Found) 127.0.0.1/:123 GET http://127.0.0.1:8000/static/neo4j/avatar2.png 404 (Not Found) 127.0.0.1/:143 GET http://127.0.0.1:8000/static/neo4j/avatar6.png 404 (Not Found) 127.0.0.1/:133 GET http://127.0.0.1:8000/static/neo4j/avatar4.png 404 (Not Found) 127.0.0.1/:138 GET http://127.0.0.1:8000/static/neo4j/avatar5.png 404 (Not Found) given the directory and images are available -
Javascript code doesn't work in Django project
I built an app using Django 3.2.3., but when I try to settup my javascript code for the HTML, it doesn't work, then I thought it could be the location of the static file the issue, and as you can see I have created two static files, with no successfull result. If you could lend me a hand I'll be very thankful. I'm using the following configuration: BASE_DIR = Path(__file__).resolve().parent.parent FORMULARIO_DIR = BASE_DIR / 'formulario' STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'static', FORMULARIO_DIR / 'static', ] Javascript settup in HTML {% load static %} <!DOCTYPE html> <html lang='es'> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet"> <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" type="text/css" href= "{% static 'formulario/style.css' %}"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script type="text/javascript" src="{% static 'scriptequipo.js' %}"></script> <title>Análisis de Infraestructura</title> </head> And here is how is organized the Django Proyect ├───formulario │ ├───migrations │ │ └───__pycache__ │ ├───static │ │ └───formulario │ ├───templates │ │ └───formulario │ └───__pycache__ └───Portfolio ├───static └───__pycache__ -
Django Media Files on Production without third party (Ex: S3 storage )
I have finished my private project, after I set debug to False, everything was broken, yet I fixed the static files with WhiteNoise but not working with media files. I have been searching and the answers are always the same... Use S3. Since I don't want to use S3, are there any solutions to store tons of images uploaded by the users -
error : set_model() missing 1 required positional argument: 'model'
I've created an emotion detection Model with resnet50 and I'm using the Adam optimizer. However, I get the following error TypeError: set_model() missing 1 required positional argument: 'model' And here's my code to create a model: # Build model on the top of base model model = Sequential() model.add(base_model) model.add(Dropout(0.5)) model.add(Flatten()) model.add(BatchNormalization()) # fully connected layer-1 model.add(Dense(128, kernel_initializer = 'he_uniform')) model.add(BatchNormalization()) model.add(Activation('relu')) model.add(Dropout(0.5)) # fully connected layer-2 model.add(Dense(64, kernel_initializer = 'he_uniform')) model.add(BatchNormalization()) model.add(Activation('relu')) model.add(Dropout(0.5)) # fully connected layer-3 model.add(Dense(32, kernel_initializer = 'he_uniform')) model.add(BatchNormalization()) model.add(Activation('relu')) # output layer model.add(Dense(7, activation = 'softmax')) # model Summary model.summary() # compile model model.compile(optimizer= 'Adam', loss='categorical_crossentropy', metrics=metric) # model fitting history = model.fit_generator(train_generator, validation_data=test_generator,epochs=60,verbose = 1,callbacks=callbacks) please help me -
Product is not adding in cart 'Django Administration'
I'm unable to add the product in cart. I want to see the product is adding to cart or not. but the process is not happening. I'm using Django as backend, PostgresSQL as DB and HTML, CSS and Javascript as backend. The Codes Goes here: views.py PRODUCT DETAIL class product_detail(View): def get(self, request, pk): product_detail = Product.objects.get(pk=pk) return render(request, 'detailpage/productdetail.html', {'product_detail':product_detail}) ADD TO CART def addProduct(request): user = request.user product_id = request.GET.get('product_id') product_cart = Product.objects.get(id=product_id) Cart(user=user, product=product_cart).save return render(request, 'cart/addtocart.html') urls.py app_name = 'main' urlpatterns = [ path('product_detail/<int:pk>', views.product_detail.as_view(), name='product_detail'), path('addProduct/', views.addProduct, name ='addProduct'), ] productdetail.html ... <form action="/addProduct"> <input type="hidden" name="product_id" value="{{product_detail.id}}" id="product_id"> <button type="submit" class="btn btn-info">Add</button> </form> ... models.py class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) def __str__(self): return str(self.id) url pattern in address bar after hitting add button http://127.0.0.1:8000/addProduct/?product_id=2342 But after this also the product is not adding in Django cart