Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error: Can't adapt type ExpressionWrapper when trying to get a Float/Decimal value
I was trying to show the distance between the user's coordinates and all coordinates in the database (student dormitories in this case) but for some reason getting the latitude and longitude of each entry gave an error as shown in the title. Code: class SohaeDormNearbyView(generics.ListAPIView): serializer_class = serializers.SohaeDormSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) queryset = models.SohaeDorm.objects.filter(is_active=True) def get_queryset(self): # Get latitude and longitude from user lat1 = self.kwargs['user_latitude'] lon1 = self.kwargs['user_longitude'] lat2 = ExpressionWrapper(F('dorm_latitude'), output_field=FloatField()) lon2 = ExpressionWrapper(F('dorm_longitude'), output_field=FloatField()) """ STOP! Before running, add the following stored procedure! CREATE FUNCTION sohae_calculate_distance5(u_lat float, u_lng float, d_id integer) RETURNS float AS $$ SELECT (6367*acos(cos(radians(u_lat)) *cos(radians(dorm_latitude)) *cos(radians(dorm_longitude) -radians(u_lng)) +sin(radians(u_lat))*sin(radians(dorm_latitude)))) AS distance FROM sohaegeum_sohaedorm WHERE id = d_id $$ LANGUAGE SQL; """ return models.SohaeDorm.objects.annotate( # Add the distance in KM as an attribute distance=RawSQL( "SELECT calculate_distance(%s, %s, %s, %s) AS distance", (lat1, lon1, lat2, lon2) ) ).filter(is_active=True) Traceback gave me the following: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/api/v1/sohaegeum/dorms/nearby/8.238479/124.243347/ Django Version: 2.0.6 Python Version: 3.6.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'rest_auth.registration', 'api', 'sohaegeum'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\mario\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py" in _execute 85. return self.cursor.execute(sql, params) The above exception (can't adapt type … -
django filter the table by date and cheque no and make a table of searched output in html table
how to filter a table that is list type by any random date and random cheque no like cheque no from 10 to 15 and cheque date from 2/1/2016 to 4/2/2016 how i impliment this in django #views.py def all_reports(request): reports = [] for model in (Mvouchar, Mycheque): for report_obj in model.objects.all(): reports.append({'topay': report_obj.to_pay, 'chequeno': report_obj.cheque_no, 'chequedate': report_obj.cheque_date, 'date': report_obj.dated}) return render(request, 'cheque/report.html', {'reports': reports}) #models.py class Mycheque(models.Model): to_pay = models.CharField(max_length=250, null=True, blank=True) amount = models.CharField(max_length=10000, null=True, blank=True) amount_in_words = models.CharField(max_length=10000, null=True, blank=True) vouchar_no = models.CharField(max_length=50, null=True, blank=True) dated = models.DateField(max_length=10, null=True, blank=True) cheque_no = models.CharField(max_length=50, null=True, blank=True) cheque_date = models.DateField(max_length=10, null=True, blank=True) account_no = models.CharField(max_length=50, null=True, blank=True) def __str__(self): return self.to_pay + ' _ ' + self.amount + ' _ ' + self.cheque_no + ' _ ' + str(self.dated) + ' _ ' + self.account_no + '_' + str(self.cheque_date) class Mvouchar(models.Model): bill_no = models.CharField(max_length=250, null=True, blank=True) bill_details = models.CharField(max_length=10000, null=True, blank=True) am = models.CharField(max_length=10000, null=True, blank=True) textarea = models.CharField(max_length=1000, null=True, blank=True) to_pay = models.CharField(max_length=50, null=True, blank=True) cheque_no = models.CharField(max_length=10, null=True, blank=True) am1 = models.CharField(max_length=50, null=True, blank=True) dated = models.DateField(max_length=10, null=True, blank=True) cheque_date = models.DateField(max_length=10, null=True, blank=True) def __str__(self): return self.bill_no + '_' + self.bill_details + '_' + self.am + … -
Django: search bar for two related models
I've got the two following models: class Topic(models.Model): alpha = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) class Entry(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE) gamma = models.TextField() date_added = models.DateTimeField(auto_now_add=True) I want to create a search bar on variables alpha (from model Topic) and gamma (from model Entry) simultaneously, thus, when using 'distinct' function, I won't have duplicates. So far I can create a search on either one, but not both at the same time. def my_view(request): '''Page displaying all topics''' topics = Topic.objects.all() entries = Entry.objects.all() #Search bar query = request.GET.get("q") if query: topics = topics.filter(Q(alpha__icontains=query)).distinct() Thx for help. -
Hi everyone, I am newly learning django. now I face an error while installing sentry in docker. Please kindly have...thank in advance :)
Starting epromotion_backend_postgres_1 ... done Starting epromotion_backend_django_1 ... done Attaching to epromotion_backend_postgres_1, epromotion_backend_django_1 postgres_1 | LOG: database system was shut down at 2018-09-08 03:06:36 UTC postgres_1 | LOG: MultiXact member wraparound protections are now enabled postgres_1 | LOG: autovacuum launcher started postgres_1 | LOG: database system is ready to accept connections django_1 | Traceback (most recent call last): django_1 | File "/usr/local/lib/python3.5/logging/config.py", line 378, in resolve django_1 | found = self.importer(used) django_1 | ImportError: No module named 'raven' django_1 | django_1 | The above exception was the direct cause of the following exception: django_1 | django_1 | Traceback (most recent call last): django_1 | File "/usr/local/lib/python3.5/logging/config.py", line 558, in configure django_1 | handler = self.configure_handler(handlers[name]) django_1 | File "/usr/local/lib/python3.5/logging/config.py", line 708, in configure_handler django_1 | klass = self.resolve(cname) django_1 | File "/usr/local/lib/python3.5/logging/config.py", line 391, in resolve django_1 | raise v django_1 | File "/usr/local/lib/python3.5/logging/config.py", line 378, in resolve django_1 | found = self.importer(used) django_1 | ValueError: Cannot resolve 'raven.contrib.django.raven_compat.handlers.SentryHandler': No module named 'raven' django_1 | django_1 | During handling of the above exception, another exception occurred: django_1 | django_1 | Traceback (most recent call last): django_1 | File "/app/manage.py", line 10, in django_1 | execute_from_command_line(sys.argv) django_1 | File "/usr/local/lib/python3.5/site-packages/django/core/management/init.py", line 353, … -
django : How to disable datepicker dates, based on the entries form db?
I have n number of dates defined in this below model in the database, these are directly inserted by admin, not by modelforms or anything. class Calendar(models.Model): date = models.DateField() occasion = models.CharField(max_length = 20) the form that has the date fields, class LeaveRequestForm(ModelForm): class Meta: fields = (... "from_date", "to_date" ...) model = Leave widgets = { ... 'from_date' : DateInput(attrs={'class': 'datepicker'}), 'to_date' : DateInput(attrs={'class': 'datepicker'}), ... } I have this datepicker script which disable weekends, <script> $(document).ready(function() { $('.datepicker').datepicker( { minDate : 0, beforeShowDay : $.datepicker.noWeekends } ); }); </script> Now I want to disable the dates defined in the database + weekends as well. How do I do that? -
Django - How to pass model instances or their attributes from a template to a view?
I want to pass a Book model instance or its attributes (like id) from a detail view template to a list view. I don't mind using which one, as long as it works. I think passing a whole object can be expensive if the model has many fields. On the other hand, passing attributes seems more effective. I don't know how to pass values without using an HTML input tag or tags used in a form tag. book/views.py: class BookDetailView(generic.DetailView): template_name = 'book/detail.html' model = Book book/templates/detail.hmtl: <form name="addToCart" action="{% url 'cart:items' %}"> {% csrf_token %} <select name="quantity"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> <option>6</option> </select> <button type="submit"> Add to Cart</button> </form> cart/models.py: class BooksInCart(models.Model): cart = models.ForeignKey('Cart', on_delete=models.CASCADE) book = models.ForeignKey(Book, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return self.book.title cart/views.py: class ItemListView(generic.ListView): template_name = 'cart/items' model = BooksInCart def get_queryset(self): queryset = super().get_queryset() book_id = self.request.POST.get('???') # the one I want to be passed from a template quantity = self.request.POST.get('quantity') book = Book.objects.get(id=book_id) cart = Cart.objects.get(user=self.request.user) return queryset.objects.creat(cart, book, quantity) -
Assign a URL to a python script to run a cron job on Google Cloud?
I have a simple Django app that displays some data it pulls from a database. I have a Python script that updates the data and I would like it to run every day. I'm having trouble figuring out how to format my app.yaml handlers so they respond to the cron.yaml. cron.yaml looks like this: cron: - description: "daily update" url: /go schedule: every 24 hours the app.yaml looks like this (minus some sensitive parts): runtime: python entrypoint: gunicorn -b :$PORT rcg_new.wsgi # specific to a GUnicorn HTTP server deployment env: flex handlers: - url: /static static_dir: static - url: /go script: scripto.app runtime_config: python_version: 3 the script looks like this: import pandas as pd import numpy as np import requests import webapp2 import urllib2 import urllib3 import certifi import json import re from rcg_func_dj import pull_rc, pull_artists, artist_cycle, tally import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "rcg_new.settings") import django django.setup() from rcg_app.models import Gender, Groups http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where()) spot_id = os.environ['SPOT_ID'] spot_sec = os.environ['SPOT_SEC'] class update_dbs(webapp2.RequestHandler): def get(self): self.response.headers["Content-Type"] = "text/html" self.response.write('running rcg...') rc = pull_rc(spot_id, spot_sec) artists_unprocessed = pull_artists(rc) artists_processed = artist_cycle(artists_unprocessed) tally(artists_processed) self.response.write('rcg done!') routes = [('/go', update_dbs)] app = webapp2.WSGIApplication(routes, debug=True) the script works, as i used it to populate … -
How do I fix <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)> in Python?
I have a Django web app that used to work when I had Python installed with Conda. I have recently uninstalled Conda and installed all my Python packages regularly. I'm trying to run my Django app on a local server and it no longer works. I've discovered the problem is this error: URLError at /submit/ <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)> Request Method: POST Request URL: http://127.0.0.1:8000/submit/ Django Version: 2.1.1 Exception Type: URLError Exception Value: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)> Exception Location: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py in do_open, line 1320 Python Executable: /Library/Frameworks/Python.framework/Versions/3.6/bin/python3 Python Version: 3.6.5 I understand there have been some updates regarding certificates with Python 3.6 (see bottom of this article). I am hoping to find a simple fix to allow me to continue running this Django app on a local host, and I'm hoping to continue using Python 3.6 without Conda. I could try using a virtualenv with a different version of Python installed but I'd like to know if I can still use 3.6. Any insights are appreciated! -
Django: What is the reason for nested template directory structure?
The django template folder requires creating a subfolder with the name of the app which then contains the template files. Why is this necessary, when python manage.py collectstatic can infer this information while traversing all directories? It seems very redundant. -
serving Django static files with nginx and gunicorn on kubernetes
I have Django application with Docker, nginx and gunicorn. I am trying to use nginx to serve the static files but I am getting 404. here is my nginx.conf: events { worker_connections 1024; } http { upstream backend { ip_hash; server backend:8000; } server { location /static { autoindex on; alias /api/static; } location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://backend; } listen 80; } } kubernetes manifest file: Nginx and app are two separate containers within the same deployment. apiVersion: extensions/v1beta1 kind: Ingress metadata: name: backend namespace: staging labels: group: backend annotations: nginx.ingress.kubernetes.io/rewrite-target: / spec: rules: - host: <host name> http: paths: - path: / backend: serviceName: backend servicePort: 8000 --- apiVersion: v1 kind: Service metadata: name: backend namespace: staging labels: group: backend spec: selector: app: backend ports: - port: 8000 targetPort: 8000 name: backend - port: 80 targetPort: 80 name: nginx --- apiVersion: extensions/v1beta1 kind: Deployment metadata: name: backend namespace: staging labels: group: backend spec: replicas: 1 template: metadata: labels: app: backend group: backend spec: containers: - name: nginx image: <image> command: [nginx, -g,'daemon off;'] imagePullPolicy: Always ports: - containerPort: 80 - name: backend image: <image> command: ["gunicorn", "-b", ":8000", "api.wsgi"] imagePullPolicy: … -
How do I run a test in Django using production data (Read only)?
I would like to run a test in Django but in order to run the test I need access to data from the production database (I don't want to setup an entirely new database for testing). How can use this data from the production database without allowing write access in my script? I don't want this test to effect anything, but I need access to this data in order to run this test. It seems ridiculous to have to launch (and pay for) an entirely new database just to grab a few rows of data, any advice? -
Test Django user profile one-to-one link
I'm adding a Profile to my Django app as a way to store more User information. Following https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html#onetoone However I'm getting an error. I'm using the default User model from django.contrib.auth. models.py from django.db import models from django.contrib.auth import get_user_model from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) @receiver(post_save, sender=get_user_model()) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=get_user_model()) def save_user_profile(sender, instance, **kwargs): instance.profile.save() tests/test_model.py from django.test import TestCase from app.models import Profile class ProfileModelTests(TestCase): @classmethod def setUpTestData(cls): Profile.objects.create() def setUp(self): pass def test_can_create_profile(self): pass error /Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. """) ..........E............ ====================================================================== ERROR: setUpClass (project-api.polls.tests.test_models.ProfileModelTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: null value in column "user_id" violates not-null constraint DETAIL: Failing row contains (158, null). The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/test/testcases.py", line 1002, in setUpClass cls.setUpTestData() File "/Users/user/programming/gatsby/project-api/polls/tests/test_models.py", line 86, in setUpTestData Profile.objects.create() File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/user/.local/share/virtualenvs/project-api-HgI9cQzm/lib/python3.6/site-packages/django/db/models/query.py", … -
Error because object attribute does not exist, except it does
I am trying to send an email using the SendGrid python API. In order to do so I use this function: def send_contact_us_email(sender=None, name=None, subject=None, message=None): status_code = None if sender and name and subject and message: to = "test@test.com" email = Email.objects.create(to=to, sender=sender, subject=subject, content=message) status_code = email.send() return status_code So I use an Email model to store emails for later potential reference and so that the code for sending an email can be put in the model. Here is the Email model: from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import * sg = SendGridAPIClient(apikey=getattr(settings, 'SENDGRID_API_KEY')) class Email(models.Model): to = models.EmailField(max_length=100) sender = models.EmailField(max_length=100) subject = models.CharField(max_length=100) content = models.TextField() def __str__(self): return 'to: {to} from: {sender}'.format(to=self.to, sender=self.sender) def send(self): if self.to and self.sender and self.subject and self.content: to_email = Email(self.to) from_email = Email(self.sender) content = Content("text/html", self.content) mail = Mail(from_email, self.subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) return response.status_code return 600 # incomplete information, cannot send email. When I run this code I expect it to work fine; I create an email model object with all required data to send an email and then use the sendgrid helper classes to construct a JSON request body for the SendGrid API to … -
Change Django Rest Framework Paginated Output Format
When serializing and paging using DRF the output of the API assumes the following format. { "count": 4429, "next": "http://127.0.0.1:8000/data/component_log/?limit=100&offset=100", "previous": null, "results": [{...},{...},{...}] } This includes the count, next, and previous fields as well as the results field. Is there any way to serialize and paginate while only returning the results array? eg [{...},{...},{...}] My Serializer class InvoiceSerializer(serializers.ModelSerializer): class Meta: model = Invoice fields = '__all__' My ViewSet class InvoiceViewSet(viewsets.ModelViewSet,UpdateModelMixin): queryset = Invoice.objects.all() serializer_class = InvoiceSerializer filter_backends = (OrderingFilter,) Without paging you are able to achieve this with the following added to the REST_FRAMEWORK setting. REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer' ), } but this does not carry over to paged requests. -
Django ORM: how to filter one model by multiple rows in a related second model
I have these two models: class Modem(models.Model): mac = Models.LowerCaseCharField class DHCPEvent(models.Model): timestamp = models.DateTimeField() # date released modem = models.ForeignKey(Modem) ip = models.LowerCaseCharField() The time window of when an IP is assigned to a given modem A is: [timestamp when IP assigned to modem A, timestamp when IP is assigned to another modem). I want to be able to query for all IP assignments to a specific modem overlapping a search time window (modem, from_date, to_date -> [ips]). To do this, I believe I need to find DHCPEvents assigned to a modem before the time window ends, and then, for each one, confirm there is no DHCPEvent for its IP assigned elsewhere before the search time window starts. This defines that the IP-to-modem assignment overlaps with the search window. But I am not sure how to do this in Django. What I have so far is this: Modem.objects.filter( dhcpevent__ip=Subquery( DHCPEvent.objects.filter( ip=OuterRef('dhcpevent__ip'), timestamp__gt=OuterRef('dhcpevent__timestamp'), timestamp__lte=to_date))) There are two issues: It is throwing "ValueError: This queryset contains a reference to an outer query and may only be used in a subquery." It seems to be inside a subquery to me. I need the OuterRefs to only look at the DHCPEvent first referenced … -
Django management command arguments
I'm trying to understand how Django management commands work. When there's no argument, or self on it's own. my command works fine. When I add arguments to the second function 'def add_arguments' it seems one arg works but the other isn't registering. My command is as follows: from backend.tasks import MBCommand import sys class Command(MBCommand): help = 'Refreshes MB data' def add_arguments(self , parser): parser.add_argument('event_id' , nargs='+' , type=int, help='evid') parser.add_argument('market_id', nargs='+', type=int, help='marid') def handle(self, *args, **kwargs): self.mb_get_events() event_ids = kwargs['event_id'] market_ids = kwargs['market_id'] for event_id in event_ids: for market_id in market_ids: self.mb_get_runners(event_id,market_id) sys.exit() My two functions are, from django.core.management.base import BaseCommand, CommandError class MBCommand(BaseCommand): def mb_get_events(self): do something def mb_get_runners(self, event_id, market_id): do something How do positional arguments work? -
Send request from google maps python api
I'm doing a service in Django, which uses the optimization of routes in a tour, I'm using the Google Maps API for it. I have read the API documentation of Google Maps Directions to optimize routes. I use the function as it is to perform tests of the following link: https://github.com/googlemaps/google-maps-services-python/blob/master/googlemaps/directions.py The function generates the parameters correctly, but when I send the request in postman, the following error appears: 'DeliveryLotDao' object has no attribute '_request' I have been looking at the documentation but an example of the API does not appear. How can I send the request correctly so that it generates the optimized routes? -
Batch process a Queryset to avoid database connection timeout
I've got a process which imports data from a CSV file then processes the data to run various calculations & set values. Imported objects generally number in the tens of thousands so celery handles the process, first it imports the data, then it runs a query to process the data. When dealing with large sets of data the processing phase has been kicking up a good old MySQL has gone away. The code was along the lines of; class ImportFile(models.Model): category = models.ForeignKey('category') file = models.FileField() def import_file(self): result = import_data(self.file) if not result.has_errors(): self.process_data() def process_data(self): results = Result.objects.select_related('user').filter( category=self.category ).order_by('finish_time') for result in results: calculate_points(result) bulk_update(results, update_fields=['points']) As I understand it, when you make a query you've got the length of CONN_MAX_AGE to finish working with that queryset before the connection times out. So I've implemented a process to take the queryset in batches to increase the chance of completing within the given time. CONN_MAX_AGE was initially set to 100 so I increased to 300 but this alone hasn't helped. So to split the process into smaller querysets I change the above to do something like; def chunks(l, n): for i in range(0, len(l), n): yield l[i:i+n] ... … -
DisallowedHost at / Invalid HTTP_HOST header: 'www.example.com'. You may need to add 'www.example.com' to ALLOWED_HOSTS
I have deployed a Django project in digitalocean ubuntu 16.04.My domain name is like example.com Because I want to add www. in front of my domain name so that if input www.example.com it can also direct to my website. I first added www.example.com in my digitalocean DNS records to let www.example.com direct to my ip address. Then I added www.example.com to myproject.setting in django to ALLOWED_HOSTS = ['.example.co','www.example.com'] Third I went to sudo nano /etc/nginx/sites-available/myproject to add www.example.com in nginx server { listen 80; server_name example.com www.example.com; } Then I test and restart nginx and gunicorn without any issue. But I still received the issue DisallowedHost at / Invalid HTTP_HOST header: 'www.example.com'. You may need to add 'www.example.com' to ALLOWED_HOSTS when use www.example.com Only example.com works. Any friend can help? Thank you so much! -
annonate don't display in template with set
This view work but the comments anotation are not display in my template with {{ comment.like_count }} but i show var in django-debug toolbar def feed(request): context = {} articles = Article.objects.select_related('user__profil')\ .prefetch_related('comments__user__profil', 'hashtags', 'comments__likes')\ .annotate(like_count=Count("likes__sum_rating()"), \ liked=Subquery(Like.objects.filter(user=request.user, content_type=7, object_id=OuterRef('pk')).annotate(cnt=Count('pk')).values('cnt'), output_field=BooleanField()), bookmarked=Subquery(Bookmark.objects.filter(user=request.user, article=OuterRef('pk')).annotate(cnt=Count('pk')).values('cnt'), output_field=BooleanField()), ).all()[:5] for a in articles: comments = Comment.objects.filter(articles=a.id).annotate(like_count=Count("likes__sum_rating()"), \ liked=Subquery(Like.objects.filter(user=request.user, content_type=9, object_id=OuterRef('pk')).annotate( cnt=Count('pk')).values('cnt'), output_field=BooleanField()), test=Count(1) ).all()[:2] a.comments.set(comments) context['activate'] = "feed" context['articles'] = articles return render_to_response(template_name='feed.html', context=context) -
Find all objects user has permissions on in Django ORM
I am using guardian for object level permissions. I need to find all objects of a given type that user can access. For example, I have an organization model called Org. A user can belong to multiple organizations and might have different level of access in them. I can find what organizations the user belongs to by doing a guardian shortcut get_objects_for_user(user, 'org_user') but this results in 5 SQL queries and I need to do this a lot. I can do the same thing in raw SQL like this SELECT o.* FROM guardian_userobjectpermission as op JOIN auth_user as u ON (op.user_id = u.id) JOIN auth_permission as p ON (op.permission_id = p.id) JOIN org_org as o ON (o.id = op.object_pk::integer) WHERE u.id = %s AND p.codename = 'org_user and use Org.objects.raw() with this SQL to get the model instances. But this is not robust, since if the models change, the SQL might break. I would love to do the same thing in Django ORM, but I cannot seem to figure out how to do this type of multiple JOIN and how to request one type of object by selecting from another. Is there a way to do this in Django ORM … -
Django Auth: "This field is required"
I want to integrate my own form to the django Auth system. It throws always an error: login This field is required. password This field is required. Setting an Debug-Point on if request.method == 'POST': didn't worked (except on page starting/loading). settings.py: AUTH_USER_MODEL = 'Immo.ImmoUser' ImmoUser class: from django.contrib.auth.models import AbstractUser class ImmoUser(AbstractUser): pass form: <form class="form-signin" action="index" method="post" style="/*! height: 100%; */margin-top: 20%;"> <img class="mb-4" src="{% static 'Immo/images/houses.png' %}" style="background-color: black; padding: 5px;border-radius: 10px;" alt="" width="72" height="72"> <h1 class="h3 mb-3 font-weight-normal">Please sign in</h1> {% csrf_token %} {{ form.errors }} <label class="sr-only" for="{{ form.username.auto_id }}">{{ form.username.label }}:</label> <input id="{{ field.username }}" class="form-control" style="margin-bottom:3px;" autofocus="" placeholder="Login*" required="" type="text"> <label class="sr-only" for="{{ form.password.auto_id }}">{{ form.password.label }}:</label> <input id="{{ field.password }}" class="form-control" style="margin-bottom:3px;" autofocus="" placeholder="Password*" required="" type="password"> <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button> <p class="mt-5 mb-3 text-muted">© 2017-2018</p> </form> views.py: def mylogin(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=raw_password) return redirect('Immo/user/index') else: form = UserCreationForm() return render(request, 'Immo/index.html', {'form': form} ) -
Trouble closing and reopening MySQL connection after catching/handling django.db.utils.OperationalError (2013, Lost connection to server)
I getting a django.db.utils.OpertionalError: (2013, Lost connection to MySQL Server). The reason is because the MAX_TIMEOUT is set to 90 seconds. I'm attempting to catch the error, close the bade connection, and make a fresh query. I would think the following try/except block would catch the error, close the connection and try the same query a second time: try: sku = SkuLight.objects.filter(expansion=card_set).filter(name=card_name) except OperationalError as e: print(e) connection.close() sku = SkuLight.objects.filter(expansion=card_set).filter(name=card_name) Am I not closing the connection correctly? If not, how can I close and reopen the connection in the correct way. Thanks. -
When and how is the .sock file created for a uWSGI, nginx and Django stack
I know that there are dozens of questions about this that mostly stem from following the official uWSGI guide. I have had troubles with permissions too but the other answers have covered them. I want to better understand how and when the Unix socket/socket file is created. FYI this is on an AWS ec2 instance running the Amazon Linux 2 AMI. The uWSGI guide instructs you to install nginx, Django and uwsgi. Then test the Django development server and nginx in isolation. Then at this section you test that uWSGI and nginx work together with a tcp/ip socket for communication. After that, still not involving the Django project at all, they describe how to use Unix sockets rather than the tcp/ip socket for communication between nginx and uWSGI. Following all of the nginx/uWSGI configuration you run the command from the home directory (at least for my particular file structure and Django project, ~/test_project): uwsgi --socket test_project/test_project.sock --wsgi-file test.py This works fine once some permission issues are dealt with. My questions are: what is test_project.sock, when is it created, and which process creates it. My best current understanding is that uWSGI creates it, but why then do we need to incorporate … -
Item edit request in database design
I'm developing simple CRUD app in Django. The app allows users to manage list of items. Let's assume that single item in database consists of following fields: ID Name Type Description Assigned_to (worker_id) Beyond that there are two kinds of users - managers and workers. Managers can freely see/add/edit/remove/assign all items. Worker can see all items, but any change made (add/edit/unassign) needs to be accepted by manager. Here's the problem. I wonder what could be the best way to implement this requirement. I came up with simple "ticket" system - every time worker sends edit request, ticket is created and can be reviewed by manager later. Ticket would be a simple object with following fields: Type (add, edit, unassign) New Item id (in case of add, edit operation) Old item id (in case of edit operation) Along with ticket, new item would be created (with all changes made and additional is_active field set to False). When manager accepts ticket, this is what would happen: Add operation - is_active is set to True Edit operation - all fields from New Item are rewritten to Old Item and New Item is deleted Unassign operation - assigned_to fields is set to Null The …