Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Where should i put Django Signals?
Hey I apologize in advance for my English. I use Django Signal in my models.py to delete user images from my media directory. Everything works great but in Django documentation I have found something like this: Where should this code live? Strictly speaking, signal handling and registration code can live anywhere you like, although it’s recommended to avoid the application’s root module and its models module to minimize side-effects of importing code. In practice, signal handlers are usually defined in a signals submodule of the application they relate to. Signal receivers are connected in the ready() method of your application configuration class. If you’re using the receiver() decorator, import the signals submodule inside ready(). Soo my questions is where and how I should properly use Django signals and what kind of consequences may be if I still used Singals In my models.py I also have found this topic: Where should signal handlers live in a django project? but it was for django 1.7 and may be a little out dated. -
Django Query to get all parents given only the child's id
Given the Table X: id | parentId | name ===================== 1 | null | A 2 | 1 | B 3 | 2 | C 4 | null | D How could I get all the connected parents until the final parent has a parentId of null. So for example, In my query I would do a pass a single id 3. This query would return row 3, row 2(because it is the parent of 3), and row 1 (because it is the parent of 2), then be done because row 1's parentId is null. Is there a way to do this without having to write in loops in the frontend to query for every parent? -
how to if condition on Foreign Key in Django
this is my model class MainCategories(models.Model): name = models.CharField(null=True,blank=True,max_length=150) def __str__(self): return u'{0}'.format(self.name) class SubCategories(models.Model): main_category = models.ForeignKey(MainCategories,null=True,blank=True,related_name = 'MainCategories', on_delete=models.CASCADE) name = models.CharField(null=True,blank=True,max_length=150) def __str__(self): return u'{0}'.format(self.name) this my view.py def home(request): sub_category = SubCategories.objects.all() print('subbbb', sub_category) c = { 'sub_category' : sub_category } return render(request,'core/home.html', c) this is my base.html <li> <a href="javascript:;">Process Equipment & Project Division<i class="fa fa-angle-right"></i></a> <ul class="sub-menu left"> {% if sub_category.Main_category.Name == "Process Equipment & Project Division" %} {% for sub in sub_category%} <li><a href="header-style-1.html">{{sub.name}}</a></li> {%endfor%} {%endif%} </ul> </li> iam created if condition in "li" tag. but its not working. the if condition is not properly.. -
Remove Group of Permissions in Django
I have list of users where the admin can add/remove group of permissions for them. When I want to add everything works fine but when removing it gives me a success method but nothing is removed. def add_remove_role(role_id, user_id, is_checked): ''' add/remove role for a user @param role_id: id of role to be removed or added @param user_id: id of user that should add or remove for him a role @param is_checked: if true then add role else remove role ''' try: user = User.objects.filter(id=user_id).first() role = Group.objects.get(id=role_id) role.user_set.add(user) if is_checked else role.user_set.remove(user) log.debug('successfully added/removed the role "%s" for user "%s" ' %(role_id, user_id)) return True except Exception as e: log.error('an error has occurred while adding/removing role of id "%s" for user "%s" ' %(role_id, user_id)) return False -
Signature differs from overidden 'save' method, pylint(signature-differs)
Could I get some help understanding what the pylint message Signature differs from overidden 'save' method, pylint(signature-differs) is referring to?: def save(self, *args, **kwargs): """ Override the original save method and update the number of seats available """ reservations = ( Booking.objects.aggregate( num_passengers=Count("passengers") ) ["num_passengers"] or 0 ) self.seats_available = self.destination.max_passengers - reservations super().save(*args, **kwargs) The Django docs says "If you use *args, **kwargs in your method definitions, you are guaranteed that your code will automatically support those (updated method) arguments when they are added." I don't fully comprehend how signatures work but my understanding is that it's to do with making sure parameters match. In this case I don't think I have changed anything from the default save method...so what is causing the issue? -
django data migration - class variable unavailable via get_model()
I'm trying to update some database records via a Django data migration, using the following migration file: from django.apps import apps from django.db import IntegrityError, migrations def exclude_pending_drivers(apps, schema_edition): Driver = apps.get_model("team", "Driver") pending_drivers = Driver.objects.filter(type=Driver.PENDING) for driver in pending_drivers: driver.show_in_app = False Driver.objects.bulk_update(pending_drivers, ['show_in_app']) class Migration(migrations.Migration): dependencies = [ ('team', '0002_add_show_in_app_to_driver'), ] operations = [ migrations.RunPython(exclude_pending_drivers), ] I'm getting an error when I run it: AttributeError: type object 'Driver' has no attribute 'PENDING' PENDING is defined as a class variable in the model: class Driver(models.Model): PENDING = 1 CONFIRMED = 2 show_in_app = models.BooleanField(default=True) # etc I can run the exact migration code above in a manage.py shell without errors, and it also runs fine if I use from team.models import Driver instead of apps.get_model("team", "Driver") (although obviously that's not advised). What gives? It looks like the Driver class, when it's included via apps.get_model(), is different to a straight import, but surely that's not the case?? -
loading querysets of the same table name from different databases
I want to combine data from user tables in 3 different databases via django query. They have roughly the same structure, so I chose to make one unmanaged model to represent them. For testing purposes I checked the output by printing it to the console. The output however, only contains data of db1. I cannot union them, because of an indiscinctable textfield. Q: Is there anything i miss or a better method than firing a raw sql via model.objects.raw() ? Here are some files for a better overview: settings.py - same dbms DATABASES = { 'default': {...}, 'db1': { 'ENGINE': 'sql_server.pyodbc', ...}, 'db2': { 'ENGINE': 'sql_server.pyodbc', ...}, 'db3': { 'ENGINE': 'sql_server.pyodbc', ...} } } models.py - same model for 3 databases class UserProfile(models.Model): id = models.IntegerField(db_column="x", primary_key=True) user_name = models.CharField(db_column="y", max_length=255, null=True, blank=True) ... class Meta: managed = False db_table = 'Users' views.py - tested for all outputs and different order def userprofile(request): d = UserProfile.objects.using('db1').all() e = UserProfile.objects.using('db2').all() f = UserProfile.objects.using('db3').all() for row in f: print(row.id, row.user_name) ... context = {...} return render(request, 'userprofile.html', context) -
How do I get a token from Django AllAuth SocialAccount?
I'm trying to get a user account and tokens for Google Calendars as such: from allauth.socialaccount.models import SocialAccount ... account = SocialAccount.objects.get(user=request.user) token = account.socialtoken_set.all().order_by('-expires_at').first() creds.expiry = timezone.make_naive(token.expires_at) creds = Credentials( token=token.token, refresh_token=token.token_secret, However, when I try running the site I get "SocialAccount matching query does not exist." in response to the account = SocialAccount.objects.get(user=request.user) line. What is the correct way for me to get the account? -
Django app deployment through ECS with uWSGI and nginx can't find some files
I'm currently deploying a containerized Django application on Amazon ECS using uWSGI and nginx, but I'm having some issues with my proxy finding some of the static content. When I test a local proxy deployment using docker-compose it works fine, but not when it's deployed through ECS. Here's my settings.py: # Static files (CSS, JavaScript, Images) STATIC_URL = '/static/static/' MEDIA_URL = '/static/media/' STATIC_ROOT = '/vol/web/static' MEDIA_ROOT = '/vol/web/media' STATICFILES_DIRS = [ # '/var/www/static/', os.path.join(BASE_DIR, 'core/static'), ] Here's my proxy config: server { listen ${LISTEN_PORT}; location /static { alias /vol/static; } location / { uwsgi_pass ${APP_HOST}:${APP_PORT}; include /etc/nginx/uwsgi_params; client_max_body_size 10M; } } Container definition for ECS: [ { "name": "app", "image": "${app_image}", "essential": true, "memoryReservation": 256, "environment": [ {"name": "DJANGO_SECRET_KEY", "value": "${django_secret_key}"}, {"name": "DB_HOST", "value": "${db_host}"}, {"name": "DB_NAME", "value": "${db_name}"}, {"name": "DB_USER", "value": "${db_user}"}, {"name": "DB_PASS", "value": "${db_pass}"}, {"name": "ALLOWED_HOSTS", "value": "${allowed_hosts}"} ], "logConfiguration": { "logDriver": "awslogs", "options": { "awslogs-group": "${log_group_name}", "awslogs-region": "${log_group_region}", "awslogs-stream-prefix": "app" } }, "portMappings": [ { "containerPort": 9000, "hostPort": 9000 } ], "mountPoints": [ { "readOnly": false, "containerPath": "/vol/web", "sourceVolume": "static" } ] }, { "name": "proxy", "image": "${proxy_image}", "essential": true, "portMappings": [ { "containerPort": 8000, "hostPort": 8000 } ], "memoryReservation": 256, "environment": [ {"name": "APP_HOST", "value": … -
Creating Registration Form with Reactive and Bbackbone.js and use django in backend
Can someone help me. I am new to Reactive and Backbone.js . I have to create a application for candidate form for filling up all candidate details and resume upload with reactive and backbone and Used django as backend. Please suggest me how can i do this . -
Frontend Technology-> Angular and Backend technology-> Django = SaaS product
I am trying to deploy a SaaS product with the subject line mentioned tech stack. The problem I am facing is how we can dynamically map the frontend to the corresponding backend provided that these tech stacks are deployed in one server per each customer. I will be using AWS EC2 capabilities to launch the product but instead of manually mapping the frontend to the backend , I wanted to know if anyone can guide me on how to dynamically launch the frontend and backend mapped correctly to each other per user. Thanks, Winston John -
Django queryset latest object's attributes after group by
This is my model class MyLog(models.Model): email = models.EmailField() date = models.DateTimeField(auto_now_add=True) comment = models.CharField(max_length=150) What i am trying to do is group by email, then filter the query by repetitions greater than 5 after that get the comment field's value of the latest object (from latest date value). I am not able to acheive the last part. Here my query so far MyLog.objects.values("email").annotate(Count("id")).filter(id__count__gte=5) This much is correct I am getting output like <QuerySet [{'email': 'test@test.com', 'id__count': 6,}]> How can I query the latest comment ? I am not able to figure out how to query that. -
JSONDecodeError at /main Expecting value: line 1 column 1 (char 0) Django
I'm getting this error constantly. I have tried json.load/loads and dump to no avail. This is the documentation for the api https://www.arvancloud.com/docs/api/cdn/4.0#operation/reports.traffics.total The request is going through as I get a success message as a response but the json being returned throws this error. from django.shortcuts import render,redirect import requests import json import ast def dashboard(request, exception=None): url = 'https://napi.arvancloud.com/cdn/4.0/domains/{DomainName}/reports/traffics' req=requests.get(url,headers{"Authorization":"Apikey********","Contenttype":"application/json"}).json() print(req) return render(request, 'dashboard.html', {}) -
Django ORM distinct values by determined date having a MySQL DB
I want to read some logs of database with Django but I been having problems. My objective is to count how many users made requests in each day in the last 7 days. I've tried this by logs_seven_days = Log.objects.filter( created_at__gte=datetime.now()-timedelta(days=7))\ .extra({'date_of_request' : "date(created_at)"}) \ .values('date_of_request') \ .values('api_key__name') \ .distinct() \ .annotate(request_of_this_date_count=Count('id')) I was wanting something like this: distinct_user_requests date 4 2/21/2020 21 2/22/2020 5 2/23/2020 0 2/24/2020 43 2/25/2020 22 2/26/2020 -
Django MOD_WSGI Settings ? MOD_WSGI Apache2 403 You don't have permission to access this resource
I'm testing an app on Ubuntu Server 18.04(VirtualBox) before bought VPS service. This is my first deployment even if it's a test and on VB. I'm facing some kind of Apache WSGI error. Error: You don't have permission to access this resource Apache/2.4.29 (Ubuntu) Server at 192.xxx.xx.xxx Port 80 Before WSGI setup, i did run few test at 8000 port and it was running well. When i setup the WSGI on the server i can't get app running. App and venv located under /home/alp/diricanelektronik directory. My server username: alp and app name is diricangrup (I did change conf file and restart apache service) My head is about to explode. You are my last hope, please help me ufw status: 22/tcp ALLOW Anywhere 80/tcp ALLOW Anywhere 22/tcp (v6) ALLOW Anywhere (v6) 80/tcp (v6) ALLOW Anywhere (v6) app home directory: (/home/alp/diricanelektronik/diricangrup) ├── contact │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── models.py │ ├── tests.py │ └── views.py ├── db.sqlite3 ├── diricangrup │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── media ├── references │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── models.py │ ├── tests.py │ └── views.py ├── … -
I've imported some mysql data into the Django mysql db. How do I get Django models to work with my existing data?
I have an existing process building data daily. I've copied tables from my main mysql to a test-mysql so I can work with the data and get it right. I found an excellent post about building the correct model python manage.py inspectdb {tablename} which was 99% correct. I have a table called main which I'd like to connect to the main model. I've 50+ tables with titles like 1234 linked by a foreign key column called G to G in main. I've just realised the way Django stores models is completely different. It stores data in tables by {appname}_{model} Have I gone about this backwards? Should I have created the Django database first, and then added to it by its conventions? I've already put a lot of work into this and it would be a lot to redo it. If its best, that's what I'll do. Thanks, T -
'Profile' object is not iterable
views.py @login_required def friends_profile(request): f_profiles = Profile.objects.get(user=request.user) return render(request, 'mains/friends_profile.html', {'f_profiles':f_profiles} ) urls.py path('friends_profile/', views.friends_profile, name='friends_profile'), template = friends_profile.html {% extends "mains/base.html" %} {% block content %} {% for friends in f_profiles %} {{ friends.full_name }} {% empty %} <li>NO DATA</li> {% endfor %} {% endblock content %} 'Profile' object is not iterable. This is raising when i open this template( friends_profiles.html ). Please... Help me in this ERROR. What am i missing in this ? -
Django REST framework api root empty
I've setup a Django REST framework project but the api root hasn't been populated with anything eg a users ViewSet and I can't access the expected url with a list of users. There is one app users, with a custom user model. (and the django project is named api) main urls.py from django.contrib import admin from django.urls import path, include from rest_framework.routers import DefaultRouter urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('users.urls')), ] the users app urls.py from django.contrib import admin from django.urls import include, path from rest_framework.routers import DefaultRouter from users.views import CustomUserViewSet router = DefaultRouter() router.register("users", CustomUserViewSet, 'users') urlpatterns = [ ] urlpatterns += router.urls users models.py from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): pass def __str__(self): return self.username users serialisers.py from rest_framework.serializers import ModelSerializer from .models import CustomUser class CustomUserSerializer(ModelSerializer): class Meta: model = CustomUser fields = '__all__' users app views.py from django.shortcuts import render from rest_framework.viewsets import ViewSet from .serializers import CustomUserSerializer from .models import CustomUser class CustomUserViewSet(ViewSet): serializer_class = CustomUserSerializer queryset = CustomUser.objects.all( And empty api root at localhost:8000/api/ and 404 error at localhost:8000/api/users/ -
Django: Ajax data changes when Django gets it
Something weird is happening to me and I don't know why: I have this data that I want to send throught ajax to django: const params = { "status__in":['pendant','confirmed'], "access_date__year":2020, "access_date__month":05, "billable":true } I use datatable to creat a table with the data that I receive, this is the ajax options for datatable: const ajax_options = { ajax: { url:get_consumptions_url, data: params } } Then I get the ajax params with this code: ajax_data = request.GET.dict() SO before trying to add an array to my params everything worked fine but when I check the ajax params debugging in python I get this: { 'access_date__month': '10', 'access_date__year': '2020', 'billable': 'true', 'status__in[]': 'confirmed' } Check "status__in" it completly changed from that I had in my params. Why is this happening? -
Occasional Client 400 Errors or Prematurely Closed Connections
I have been dealing with an issue that is rare and I can't repeat it. I have 100s of users everyday uploading files to my server. 99% of the time users are fine and have no issues uploading. Occasionally though someone will have trouble uploading and the issues seems to be client side. It can be resolved by having them go to another computer to upload. Having them clear their cache and cookies I assume would work to, but it is difficult to explain to a non technical user how to do that. I use django and manifset static files so they get cache busted anytime new scripts are added. Old scripts shouldn't be being used in their browser. I have implemented multiple methods of upload for when this happens. The standard way is an ajax single request to get a progress bar. If things fail I revert them to the most basic form request no progress bar. If that fails I also have a chunked upload method that allows them to upload in chunks. The most recent time this happened it failed on all those methods. The user received a 400 error when uploading via chunked. It seemed looking … -
Django Variable not getting showed
I have started my Djnago Journey, I am trying to print a defined variable in html file but not getting anything, please let me know whats wrong with the code my views.py, see the last method where I'm trying to post the data from django.shortcuts import render from django.http import HttpResponse, JsonResponse # Create your views here. def bootstrappage(request): return render(request, 'index.html') def secondpage(request): return render(request, 'common.html') def thirdpage(request): var = 'this is my first variable' mydictionary = { "first": var, 'two':"data of two" } print(mydictionary["first"]) return render(request, 'third.html', context=mydictionary) third.html file where I am trying to print the variable <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> </head> <body> {% extends 'index.html' %} {% block title %}Third page{% endblock %} {% block name %}Viewing Third page!{% endblock %} {{first}} {{two}} </body> </html> index.html file, this is taken from official bootstrap site, basic code of navbar. <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <title>{% block title %}bootstrap{% endblock %}</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div … -
Async logging in Django
I have created a simple weather webapp in Django using API. Logging is enabled and are written into files in Windows. I want logging to be asynchronous that is at the end of execution. How can we do async logging in Django? -
How can I install Django in my Docker file?
I am a newbie to Docker. I have created one Django project and can run it in Docker. However, I have started a second project and have encountered a problem. I created a virtual env and entered it pipenv install django~=3.1.0 && pipenv shell I created a Django project django-admin startproject config . I ran it within the virtualenv python manage.py runserver and could see the Django spaceship I then exited the virtualenv and created a Dockerfile Dockerfile # Pull base image FROM python:3.8 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system # Copy project COPY . /code/ I ran docker build . and it reported a successful build I created a docker-compose.yml file docker-compose.yml version: '3.8' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 When I run docker-compose up it complains ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I have read in the comments to this question that virtual envs should not … -
How to get rid of no carparks found for no such campus
{% if campus %} <h2>{{ campus }}</h2> {% else %} <h2>No such campus</h2> {% endif %} {% if carparks %} <ul> {% for carpark in carparks %} <li>{{carpark.name}}: {{carpark.spaces}} spaces, {{carpark.disabled_spaces}} spaces for people with disabilities <br>Spaces available: {{ carpark.spaces_available }}<br><br> </li> {% endfor %} {% else%} <p>No carparks found</p> {% endif %} </ul> This is my carparks.html code, when I type the name of a campus that is not stored in the Django database, it says both 'No such campus' and 'No carparks found'. How do I only print 'No such campus' for a campus that does not exist? -
Validating keycloak bearer token on behalf of client
I want to validate bearer tokens in an API, which are passed from a browser application. The API will validate the tokens against Keycloak by calling the ../userinfo endpoint and respond with the desired content if the check runs ok. Problem is that If I pass a bearer token from the browser, or any other app for that matter (e.g. postman), to the api and try to validate it - I get "401 Token verification failed". The following works: Fetch token from Keycloak through Postman by using username and password. Fetch userinfo from Keycloak through Postman using the resulting bearer token. OR Fetch token from Keycloak directly from the API by using username and password. Fetch userinfo from Keycloak from the API using the resulting bearer token. The following does NOT work: Fetch token from Keycloak through Postman by using username and password. Send request to API, running in a docker container, containing the bearer token. API tries to fetch userinfo using the token = "401 Token verification failed" Using same client_id and client_secret in all scenarios. Is this a docker networking thing? Or is some Keycloak configuration necessary in order for the API to validate token "on behalf" of …