Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django N+1 problem with serpy.MethodField
I use nplusone to detect N+1 queries. I have a serpy serializer that serializes Order instances. An Order has a cart consisting of OrderComponent instances, as shown below. Code simplified: class Order(models.Model): objects = OrderManager() listings = models.ManyToManyField(to=Listing, through="OrderComponent", related_name="orders") class OrderComponent(models.Model): listing = models.ForeignKey(to=Listing, on_delete=models.PROTECT, related_name="order_components") order = models.ForeignKey(to=Order, on_delete=models.PROTECT, related_name="cart") nb_units = models.PositiveIntegerField() A list of serialized Order instances is gotten through OrderListView: class OrderListView(SimplePaginatedListView): # Custom base class model = Order serializer_class = OrderSerializer deserializer_class = OrderDeserializer def get_queryset(self): return super().get_queryset().select_related( "fulfillment", # Used for order.is_fulfilled() "cancellation", # Used for order.is_cancelled() ).prefetch_related( "cart", # I don't believe the first two are necessary, but added for testing purposes "cart__listing", "cart__listing__product", "cart__listing__service", ) @http_get(required_permissions=ShopRolePermission.MANAGE_ORDERS) def get(self, *args, **kwargs): return super().get(*args, **kwargs) @http_post(required_permissions=ShopRolePermission.MANAGE_ORDERS) def post(self, *args, **kwargs): return super().post(*args, **kwargs) OrderSerializer is defined below. nplusone does not say where an N+1 query was detected, so I have commented out every possible culprit and found the true culprits. I have indicated in comments where they are. class OrderSerializer(BaseSerializer): class SimpleOrderComponentSerializer(BaseSerializer): id = serpy.IntField() listing_id = serpy.IntField() product_name = serpy.MethodField(required=False) # No N+1 service_name = serpy.MethodField(required=False) # No N+1 nb_units = serpy.IntField() def __init__(self, instance=None, many=False, data=None, context=None, **kwargs): # Should this … -
Python Django NoReverseMatch Error When I {% url 'crm_client_detail' client.id %}
I know my question seems fimiliar to others but it's not. I'm stuck on in the error in the below when I visit my homepage. The problem is that {% url 'crm_client_detail' client.id %}. I'm pretty sure that I'm doing right but it's not happening. NoReverseMatch at / Reverse for 'client_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['client/(?P[0-9]+)/$'] Any help is so appreciated models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Client(models.Model): client_name= models.CharField(max_length=100) client_sector= models.CharField(max_length=100) client_phone= models.CharField(max_length=100) client_city= models.CharField(max_length=100) client_district= models.CharField(max_length=100) client_adress= models.TextField() client_type= models.CharField(max_length=100) client_priority= models.CharField(max_length=100) client_first_contacted_date=models.DateTimeField(default=timezone.now) # author = models.ForeignKey(User, on_delete=models.CASCADE) views.py from django.shortcuts import render from .models import Client from django.views.generic import ListView, DetailView def ClientView(request): context = {'client_aranacak': Client.objects.all()} return render(request, 'crm/crm_home.html', context) class ClientListView(ListView): model = Client template_name = 'crm/crm_home.html' context_object_name = 'client_aranacak' ordering = ['-client_first_contacted_date'] class ClientDetailView(DetailView): model = Client urls.py from django.urls import path from . import views from .views import ClientListView, ClientDetailView urlpatterns = [ path('', ClientListView.as_view(), name='crm_client'), path('client/<int:pk>/', ClientDetailView.as_view(), name='client_detail'), ] # {% url 'crm_client_detail' client.id %} crm_home.html {%extends "base.html"%} {%block content%} <div class="card mb-4"> <div class="card-header"> <i class="fas fa-table mr-1"></i> Customers </div> <div class="card-body"> <div class="table-responsive"> <table … -
github action for django project
I am trying the github-action-django and the following is the python-app.YAML file for the project name: Python application on: push: branches: [ master ] pull_request: branches: [ master ] jobs: build: runs-on: ubuntu-latest services: postgres: image: postgres:11 env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: postgres ports: - 5432/tcp options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v2 - name: Set up Python 3.6 uses: actions/setup-python@v2 with: python-version: 3.6 - name: psycopg2 prerequisites run: sudo apt-get install python-dev libpq-dev - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt pip install -r devreq.txt - name: Run migrations run: python manage.py migrate --settings=mysite.dev - name: Test with pytest run: pytest while running the migration job, workflows throws following error: django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? the database setting also defined in dev.py which is used as django settings while invoking migrations DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mysite', 'USER': 'naveen', 'HOST': '127.0.0.1', 'PORT': 5432, } } if os.environ.get('GITHUB_WORKFLOW'): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'github_actions', 'USER': 'radorado', 'PASSWORD': 'radorado', 'HOST': '127.0.0.1', 'PORT': '5432', … -
Django channels websocket connecting and disconnecting (Nginx + Daphne + Django + Channels)
I'm having problems to deploy this in a production virtual machine, with Nginx + Gunicorn + Daphne + Django. I had been testing it in a local virtual machine, and it works without a problem, but in production, the sockets is connecting and disconnecting. I attached my nginx config, asgi.py and routing.py. I use the command ````$ daphne -p 8010 project.asgi:application``` enter image description here # Nginx config upstream test_project { server localhost:8001; } upstream test_project_websocket { server localhost:8002; } server { listen 1881; location / { proxy_pass http://test_project; } location /ws/ { proxy_pass http://test_project_websocket; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_redirect off; } proxy_set_header Host $host; } #asgi.py import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'WebServer.settings') django.setup() from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter import Andon.routing # app.routing from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.layers import get_channel_layer application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( Andon.routing.websocket_urlpatterns, ), ), }) # routing.py from django.urls import path, re_path from . import consumers from channels.layers import get_channel_layer websocket_urlpatterns = [ re_path(r'ws/andon/$', consumers.AndonConsumer.as_asgi()), ] -
'Profile' object is not iterable . Error is raising when i click on template
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 %} models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) full_name = models.CharField(max_length=100,default='') friends = models.ManyToManyField(User, related_name='friends',blank=True) email = models.EmailField(max_length=60,default='') date_added = models.DateTimeField(auto_now_add=True) def get_friends(self): return self.friends.all() def get_friends_no(self): return self.friends.all().count() def __str__(self): return f'{self.user.username}' STATUS_CHOICES = ( ('send', 'send'), ('accepted','accepted'), ) class Relationship(models.Model): sender = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='receiver') status = models.CharField(max_length=8, choices=STATUS_CHOICES) def __str__(self): return f"{self.sender}-{self.receiver}-{self.status}" '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 ? I will really appreciate your HELP. -
Range Filter not working in django rest does not react at all when filtered
Range Filter not working in django rest does not react at all when filtered View class MDShopListView(generics.ListAPIView): queryset = smartphone.objects.all() filter_backends = (DjangoFilterBackend,) filterset_class = ShoppFilter def get(self,request): queryset = self.get_queryset() serializer=MDShopListSerializer(queryset,many=True) return Response(serializer.data) -
Use get_queryset method with tables2
Right now, this code works to render my template as an html table, but I would like to render it as tables2. How to do that, while keeping the "get_queryset" bit in the views.py file is giving me trouble. urls.py path('proforma/<int:pk>/', ProformaDetailView.as_view(), name='proforma-detail') views.py class ProformaDetailView(ListView): template_name = "blog/proforma_detail.html" context_object_name = 'proforma' def get_queryset(self): queryset = Proforma.objects.filter(proforma_id=self.kwargs['pk']) return queryset tables.py | Not currently being used class ProformaDetailTable(tables.Table): class Meta: model = Proforma template_name = "django_tables2/bootstrap.html" fields = ('proforma_id','time_stamp','base_price','lot_cost','permit_cost','hard_cost') -
Probmlems with admin pagel in django
I have a problem with the admin panel on a project that I cloned recently in order to perform some tasks on it. I had install all the packages from requirements.txt, make migrations, created a superuser and I logged in in the admin section and I want to add some new objects in order to test some new functionality that I've added and it's not opening anything. When I click on users for example it just selects the user field and that's wall, doesn't redirect me to the users specific page. I can't add nothing. This is how it looks like when I click on a field. -
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 ?