Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Environment Variables, error: django.core.exceptions.ImproperlyConfigured: The INSTALLED_APPS setting must be a list or a tuple
I'm setting up the enviroment variables in my venv created with virtualenv. I created two scripts: postactivate and preactivate, The order of the commands that I follow are: source venv/bin/activate, source venv/bin/postactivate and python manage.py runserver but I have this error when I try to run my command python manage.py runserver : django.core.exceptions.ImproperlyConfigured: The INSTALLED_APPS setting must be a list or a tuple. Y tried some things: put the entire list in only one line, to exchange between single and double quotes, even, convert to a tuple. postactivate script export INSTALLED_APPS="[ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.humanize', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'custom_user', 'corsheaders', 'django_s3_storage', 'django_ses', 'captcha', 'embed_video', 'bootstrap_forms', 'models_simple_trans', 'tables', 'markdown_filter', 'apps.countries', 'apps.companies', 'apps.organizations', 'apps.campaigns', 'apps.auctions', 'apps.users', 'apps.home', 'apps.emails', 'apps.adminpanel', 'apps.payments', 'helpers', 'celery', 'rest_framework_swagger', 'django_extensions', 'social_django', 'mapwidgets', 'rosetta', 'channels', 'django_user_agents', 'django.contrib.sitemaps', 'django_tables2', ]" I hope you can help me. -
How to deploy django on AWS EC2 using media and static files from S3
I wanna deploy Django project on AWS EC2. For my media files, I need a bucket on S3. My project working good on localhost, and I can access media from S3, but after deploying I can't get AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY that's why I'm getting Server Error 500. This is the main part of settings.py DEBUG = False ALLOWED_HOSTS = ['XXXXXXXX'] INSTALLED_APPS = [ 'apps.comic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', ] STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'apps/comic/static/media') MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' I tried to make ~/.aws/credentials: [default] aws_access_key_id = X...X aws_secret_access_key = X...X But it's the same result Server Error 500. I can get just login/registration page because I don't have any media files on it. What should I do for getting media files after production? Do I need to make some changes in credentials or in settings.py file? -
Django ORM not generating correct SQL for many to many not in
I'm having a problem with Django's generated SQL from the ORM. Cartons have a many to many relationship with Shipments through cartons_shipments. I'm looking to exclude Shipments where they have at least one INBOUND Carton that has a status in ['TRANSIT', 'DELIVERED', 'FAILURE']. But I was not getting the results I expected so I turned on the SQL logging. return Shipment.objects.filter( ... # other filtering # does not have any inbound cartons in_transit/delivered/failed ~Q( Q(cartons__type='INBOUND') & Q(cartons__status__in=['TRANSIT', 'DELIVERED', 'FAILURE']) ) & ).distinct() This generates this SQL: AND NOT ( "shipments"."id" IN ( SELECT U1."shipment_id" FROM "cartons_shipments" U1 INNER JOIN "cartons" U2 ON (U1."carton_id" = U2."id") WHERE U2."type" = 'INBOUND' ) AND "shipments"."id" IN ( SELECT U1."shipment_id" FROM "cartons_shipments" U1 INNER JOIN "cartons" U2 ON (U1."carton_id" = U2."id") WHERE U2."status" IN ('TRANSIT', 'DELIVERED', 'FAILURE') ) ) But this isn't correct as it would exclude shipments where it has any INBOUND cartons and shipments where any carton (not necessarily INBOUND cartons) has a status is in ['TRANSIT', 'DELIVERED', 'FAILURE']. I need this logic combined. Also now I'm running 2 sub selects and taking a significant performance hit because we have a ton of cartons in those statuses. The correct SQL would be … -
TypeError: 'element_id' is an invalid keyword argument for this function
I get the following error and I can't seem to get it working: TypeError at /vxml/InputData/33/15 'element_id' is an invalid keyword argument for this function I assume it has something to do with def Input(request, element_id, session_id) in my view because that is the only place where element_id is in this view. I can't seem to find where the element_id is assigned. view: from django.shortcuts import render, get_object_or_404, get_list_or_404, redirect from ..models import * def input_get_redirect_url(input_element, session): return input_element.redirect.get_absolute_url(session) def input_generate_context(input_element, session): language = session.language redirect_url = input_get_redirect_url(input_element, session) ask_input_label = input_element.voice.label.ask_input_label_url(language) ask_confirmation_voice_label = input_element.ask_confirmation_voice_label.get_voice_fragment_url(language) final_voice_label = input_element.final_voice_label.get_voice_fragment_url(language) context = { 'InputData': input_element, 'redirect_url': redirect_url, 'voice_label' : voice_label, 'ask_input_label' : ask_input_label, 'ask_confirmation_voice_label' : ask_confirmation_voice_label, 'final_voice_label' : final_voice_label, } return context def Input(request, element_id, session_id): input_element = get_object_or_404(Record, pk=element_id) voice_service = input_element.service session = lookup_or_create_session(voice_service, session_id) if request.method == "POST": session = get_object_or_404(CallSession, pk=session_id) value = 'DTMF input' result = UserInput() result.session = session result.category = input_element.input_category result.save() return redirect(request.POST['redirect']) session.input_step(input_element) context = input_generate_context(input_element, session) context['url'] = request.get_full_path(False) return render(request, 'input.xml', context, content_type='text/xml') Model: from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext from vsdk.service_development.models import VoiceLabel from .vs_element import VoiceServiceElement from .user_input import UserInputCategory class … -
How to fix "django_1 | sentry_sdk.utils.BadDsn: Missing public key" error when docker-compose up?
If I try docker-compose up my project, it throws me out with error: django_1 | File "/usr/local/lib/python3.7/site-packages/sentry_sdk/utils.py", line 115, in __init__ django_1 | raise BadDsn("Missing public key") django_1 | sentry_sdk.utils.BadDsn: Missing public key Django version: 2.1 In .env file: DOCKER=1 DEBUG=1 My docker-composer.yml: version: "3.5" services: nginx: image: nginx restart: always command: bash -c "tail -f /dev/null" ports: - 80:80 - 443:443 volumes: - ./backend/static:/data/django/static - ./backend/media:/data/django/media - ./certs:/etc/letsencrypt/ - ./misc/ssl/server.crt:/etc/ssl/certs/server.crt - ./misc/ssl/server.key:/etc/ssl/private/server.key - ./misc/conf/nginx.conf:/etc/nginx/nginx.conf:ro depends_on: - react django: build: context: backend volumes: - ./backend/static:/data/django/static - ./backend/media:/data/django/media depends_on: - db - redis env_file: - backend/misc/.env ... I expect (1) to run my project with docker-compose up command and (2) to get a link to relevant documentation. -
Django, show specific view by time
I want to show a view by specific time. Like this time it will show on the page and close on written time. Like a promotion, special discount like a banner like that. Thank you! -
How to make a Jquery AJAX post to fill a table without ending up on the wrong url?
I need to fill a table of a given page of my Django site, say its url is /. I have an ajax code to pull the table contents from another url: /suggest/ this is the AJAX code: var frm = $('#sugg'); frm.submit(function () { $.ajax({ type: frm.attr('method'), url: frm.attr('action'), data: frm.serialize(), success: function (data) { $("#suggestion").append(data); window.location=""; }, error: function(data) { $("#MESSAGE-DIV").html("Something went wrong!"); } }); return false; }); it fetches the table html correctly but renders it on a blank page on the /suggest/ url, instead of just filling the div $('#suggestion'), and remaining on the / url. What am I doing wrong? -
How to do a LEFT OUTER JOIN QuerySet in Django - Many to One
I got two models: Image(filename, uploaded_at) and Annotation (author, quality,... fk Image). An Image can have multiple Annotations, and an Annotation belong to one image. I'd like to build a queryset that fetch all annotations (including the relation to the image so I can display image fields as well) that meet some criteria. All fine until here, but I'd like to display also the images that have no annotations created (left outer join), and not sure how could I proceed to do this? To clarify I am trying to get fetch the data so I can build a table like this: Image name, Image date, Annotation author, Annotation Quality image 1 , 2019 , john , high image 2 , 2019 , doe , high image 3 , 2019 , null , null image 4 , 2014 , doe , high Maybe I'm using wrong approach, I'm using Annotation as main model, but then I don't seem to have a way to display the images that don't have Annotation, which kind of makes sense as there is no Annotation. This is what I'm doing: Annotation.objects.select_related('image').filter(Q(image__isnull=True) | Q(other condition)) However, if I use Image as main model, the relation is many … -
NoReverseMatch at /admin/pinterest/pinner/add/
I am trying to make a project "pinterest clone". I am following the bellow link - https://github.com/sobriquette/pinclone . When I try to add a pinner I am getting this error - "NoReverseMatch at /admin/pinterest/pinner/add/" . I don't understand what's the problem. Please help me to find out. This is my models.py from __future__ import unicode_literals import uuid from django.db import models import django.utils.encoding class Pinner(models.Model): pinner_id = models.CharField(primary_key=True, editable=False, max_length=255) avatar = models.URLField(blank=True) full_name = models.CharField(max_length=128) username = models.CharField(max_length=20) def print_attr(self): for k, v in self.__dict__.items(): if '__' not in k: print("{}: {}".format(k, v)) def __str__(self): return self.username class Board(models.Model): board_id = models.CharField(primary_key=True, editable=False, max_length=255) name = models.CharField(max_length=20) pinner = models.ForeignKey(Pinner, on_delete=models.CASCADE) url = models.URLField() def print_arrt(self): for k, v in self.__dict__.items(): if '__' not in k: print("{}: {}".format(k, v)) def __str__(self): return self.name class Pin(models.Model): pin_id = models.CharField(primary_key=True, editable=False, max_length=255) board = models.ForeignKey(Board, on_delete=models.CASCADE) description = models.CharField(max_length=255, blank=True) link_count = models.IntegerField(blank=True) link = models.URLField(blank=True, null=True) title = models.CharField(max_length=128, blank=True) def print_attr(self): for k, v in self.__dict__.items(): if '__' not in k: print("{}: {}".format(k, v)) def __str__(self): return self.title class Image(models.Model): image_id = models.CharField(primary_key=True, editable=False, max_length=255) pin = models.ForeignKey(Pin, related_name='images', on_delete=models.CASCADE) url = models.URLField(blank=True, null=True) def print_attr(self): for k, v … -
How to properly format date for django via datepicker
I am trying to populate a DateTimeField on a django model. I am doing it via the frontend using this extension (https://bootstrap-datepicker.readthedocs.io/en/latest/). The problem is when i submit the form, I get this error in the console "Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]. Where could the problem lie? Model class Video(models.Model): beginDate = models.DateTimeField(default=timezone.now) Date picker <input type="text" id="from-datepicker" onChange={handleDate} data-provide="datepicker" name="beginDate" data-date-format="yyyy-mm-dd" placeholder="Select date" className="form-control lesson__startDate" required /> -
django folder path picker
I would like to find a django folder path dialog picker and store that path in a charfield as text. I'm going to use it some django form widget to do that,but i cant find anything. anyway I finally I try to use html file input to take the path as text but not work I get none in the print on the hadle models.py folder_path = models.CharField(max_length=254, blank=True, null=True) views.py folder_p = request.POST.get('file_input') print folder_p html: <input type="file" id="file_input" webkitdirectory directory multiple/> -
Django Remote_User Authentication prompting for username and password again
I implemented Remote_user authentication in Django web application (Windows Authentication). When I opened the website, it's asking me again username and password for login even its windows authentication. Followed below steps mentioned in link https://docs.djangoproject.com/en/2.2/howto/auth-remote-user/ ''' 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.auth.middleware.RemoteUserMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.RemoteUserBackend',] ''' I am not sure, what other steps I need to follow? -
Postgres Database Error results in CommandError: This script should be run from the Django Git checkout or your project or app tree
I ran into a weird error and I'm a bit stuck. I have a cookiecutter project which was running perfectly fine. Then I deployed my app to Heroku and now when I build the docker container anew and start it I get the following error: CommandError: This script should be run from the Django Git checkout or your project or app tree, or with the settings module specified. Before that I get this output which makes me assume this is a database error: The files belonging to this database system will be owned by user "postgres". postgres_1 | This user must also own the server process. postgres_1 | postgres_1 | The database cluster will be initialized with locale "en_US.utf8". postgres_1 | The default database encoding has accordingly been set to "UTF8". postgres_1 | The default text search configuration will be set to "english". postgres_1 | postgres_1 | Data page checksums are disabled. postgres_1 | postgres_1 | fixing permissions on existing directory /var/lib/postgresql/data ... ok postgres_1 | creating subdirectories ... ok postgres_1 | selecting default max_connections ... 100 postgres_1 | selecting default shared_buffers ... 128MB postgres_1 | selecting dynamic shared memory implementation ... posix postgres_1 | creating configuration files ... ok … -
How to get all values from ForeignKey relation in loop?
I have a next models: Order, OrderItem class Order(models.Model): pass class OrderItem(models.Model): order = models.ForeignKey( Order, related_name='order_item', verbose_name=_('order'), null=True, on_delete=models.SET_NULL, limit_choices_to={'enabled': True} ) views def order_view(request): user_orders = Order.objects.filter(user=request.user) How can I get all order_item values for each order? {% for order in orders %} {% for ord in orderitem.order_set.all %} 123 {% endfor %} {% endfor %} -
How to find items that are not on the right side of a OneToOneField?
I have these two models: class Location(models.Model): plate = models.OneToOneField(Plate, default=None, on_delete=models.CASCADE, null=True, blank=True) class Plate(models.Model): id = models.CharField(primary_key=True, max_length=100) As you can see, there can only be one Plate connected to a Location. But how to find all Plates, that are not assigned to a Location ? I can count them like this: models.Plate.objects.count() - models.Location.objects.filter(plate__isnull=False).count() but I need a list of Plates, not just a number. I tried to search online and in the docs, but I actually have no idea what to search for. And I do not see how I could do this with Q objects or the filter method. -
Django - How to get rid of multiple saves
I have the following model. class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=255) description = models.TextField(null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') image = models.ImageField(max_length=255, upload_to='posts/images/', null=True, blank=True) thumbnail = models.FilePathField(path=settings.MEDIA_ROOT, max_length=255, null=True, blank=True) As you can see, I need two images here, the raw image that the user uploads, and a thumbnail version that I will use on the home page. The thing is that I am creating the thumbnail on the save method using this code: def save(self, *args, **kwargs): super(Post, self).save(*args, **kwargs) # Get the thumbnail from the image if self.image: self.thumbnail = get_thumbnail(self.image, '500x500', crop='center', quality=85).url super(Post, self).save(*args, **kwargs) I can't get rid of the first super(Post, self).save(*args, **kwargs) because I want self.image to be available, and I can't get rid of the second super(Post, self).save(*args, **kwargs) because then the thumbnail won't be saved. I am pretty sure there must be another way of doing this. Could you please give me a few pointers? -
Is there a way to display a view by date?
Like if i want paragraph to be on monday. Another paragraph on tuesday, Wednesday and whole week. Please help to advice me place to get informantion! Thank you. -
DRF: Could not resolve URL for hyperlinked relationship using view name "tickettype-detail"
We want our users to be able to define the options for various select fields in our site. Those options will go in their own table (model). For the API, we have the "Ticket" model. which has a field "type" which is a ForeignKey to the "TicketType" model. I'm getting this error: Could not resolve URL for hyperlinked relationship using view name "tickettype-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. If I remove the type field from the Ticket model, the error goes away. I've read a lot of posts online about this, and tried a lot of different things, but so far haven't been able to fix it. models.py: from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ class Ticket(models.Model): summary = models.CharField( verbose_name=_('Summary'), max_length=255, ) description = models.TextField( verbose_name=_('Description'), blank=True, ) type = models.ForeignKey( 'TicketType', verbose_name=_('Type'), on_delete=models.PROTECT, ) ...other fields omitted... created = models.DateTimeField( verbose_name=_('Created'), default=timezone.now, ) class TicketType(models.Model): type = models.CharField( verbose_name=_('Type'), max_length=255, ) serializers.py from rest_framework import serializers, permissions from tickets.models import Ticket, TicketType class TicketSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="tickets:ticket-detail") permission_classes = (permissions.IsAuthenticated,) class Meta: model = Ticket … -
Python manage.py collectstatic TypeError: an integer is required (got type str)
I'm working with Django version 2.2 . When I run the command python manage.py collectststic I get the following log on bash terminal. You have requested to collect static files at the destination location as specified in your settings: /home/djapp/poorface/staticfiles This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/amit/.virtualenvs/hola/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/amit/.virtualenvs/hola/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/amit/.virtualenvs/hola/local/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/home/amit/.virtualenvs/hola/local/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/home/amit/.virtualenvs/hola/local/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 188, in handle collected = self.collect() File "/home/amit/.virtualenvs/hola/local/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect handler(path, prefixed_path, storage) File "/home/amit/.virtualenvs/hola/local/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 353, in copy_file self.storage.save(prefixed_path, source_file) File "/home/amit/.virtualenvs/hola/local/lib/python3.6/site-packages/django/core/files/storage.py", line 49, in save return self._save(name, content) File "/home/amit/.virtualenvs/hola/local/lib/python3.6/site-packages/django/core/files/storage.py", line 288, in _save os.chmod(full_path, self.file_permissions_mode) TypeError: an integer is required (got type str) I changed the permissions of the staticfiles to -rwxrwxrwx . Then also there is no change in output. manage.py looks like #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Poorface.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise … -
How do I consider an element's ancestor when parsing with BeautifulSoup?
I'm using Python 3.7, Django, and BeautifulSoup. I am currnently looking for "span" elements in my document that contain the text "Review". I do so like this html = urllib2.urlopen(req, timeout=settings.SOCKET_TIMEOUT_IN_SECONDS).read() my_soup = BeautifulSoup(html, features="html.parser") rev_elts = my_soup.findAll("span", text=re.compile("Review")) for rev_elt in rev_elts: ... processing but I'd like to add a wrinkle to where I don't want to consider those elements if they have a DIV ancestor with the class "child". So for example, I don't want to consider something like this <div class="child"> <p> <span class="s">Reviews</span> ... </p> </div> How can I adjust my search to take this into account? -
Include attributes from another referenced model in a filtered get request on django REST framework
My goal is to include the name attribute of the Brand model a Product references through models.ForeignKey, when I make a get request for products. Exactly what this piece of code returns in the python shell: Product.objects.all().values('name', 'brand__name',) returns this: [ {'name': 'B-1', 'brand__name': 'B-brand'}, {'name': 'B-2', 'brand__name': 'B-brand'}, {'name': 'C-1', 'brand__name': 'C-brand'} ] Im already using django-filters to filter my get requests. Models: class Brand(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=255) brand = models.ForeignKey(Brand, on_delete=models.CASCADE, default=None) def __str__(self): return self.name Serializers: class BrandSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Brand fields = ('id', 'url', 'name') class ProductSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Product fields = ('id', 'url', 'name', 'brand') Filter: class ProductFilter(filters.FilterSet): name = filters.CharFilter(lookup_expr = 'icontains') brand__name = filters.CharFilter(lookup_expr = 'icontains') class Meta: model = Product fields = ('name' 'brand__name',) View: class ProductView(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer filterset_class = ProductFilter with brand__name in the filterSet, i am able to reference the name of the brand model a certain product is referencing and retrieve it. My goal is to also include that same name of the Brand along with the attributes of a product when I make the get request, which currently only yields … -
Django - Session key_error
Using Django REST Framework in development, I have the following (previously working) code example, where in one view I set session data, and in another view I use that data. And like I said, this code used to work, but now for some reason the stored session data can not be accessed anymore. View for setting session data @api_view(["POST"]) @permission_classes((AllowAny, )) def set_session_data(request): session_data_dict = loads(request.body.decode('utf-8')) if not isinstance(session_data_dict, dict): return Response({"message": "Expected a JSON object with key-val pairs to be sent. Key-val pairs to be set to session. Received something else.", status: status.HTTP_400_BAD_REQUEST}) try: for key, value in session_data_dict.items(): request.session[key] = value response_data = {"status": rest_status.HTTP_200_OK} except: response_data = {"status": rest_status.HTTP_500_INTERNAL_SERVER_ERROR} return Response(response_data) View that accesses stored session data: @api_view(["GET"]) @permission_classes((AllowAny, )) def check_user_logged_in(request): try: data = {"login_token": request.session["login_token"]} except KeyError: data = {"login_token": ""} return Response(data, status=rest_status.HTTP_200_OK) I have tested a little, and I can access the data in the session in the set_session_data view, after it has been added, like so: request.session['login_token'] But when I try the same in the check_user_logged_in view, I get a KeyError. So I tried checking if the sessions for both views are the same session, by checking the value of request.COOKIES[settings.SESSION_COOKIE_NAME] in … -
How do I fix 'MultipleObjectsReturned' error in Django rest framework
I am building an API using Django rest framework. I currently have an endpoint /api/v1/device-groups/ which returns all device group objects like this: [ { "device_group_name": "Default", "group_uuid": "3812a299-3ab9-4c00-a711-d166fb01075e", "color": "4286f4", "is_default": true, "customer": { "customer_name": "Testcustomer", "customer_uuid": "179fe73d-ec67-45ac-8dac-e2456ccd9b48" } } ] Using the customer_uuid in the URL shows the device groups related to that customer /api/v1/device-groups/179fe73d-ec67-45ac-8dac-e2456ccd9b48 returns data of the device groups attached to the specified customer_uuid The problem I am facing is that whenever there are multiple device groups related to a customer_uuid it results in a MultipleObjectsReturned error. I want to list all the device groups that are related to the specified customer_uuid. My serializers.py: class CustomerSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Customer fields = ('customer_name', 'customer_uuid') class DeviceGroupSerializer(serializers.HyperlinkedModelSerializer): customer = CustomerSerializer(many=False, read_only=True, source='customer_uuid') class Meta: model = DeviceGroup fields = ('device_group_name', 'group_uuid', 'color', 'is_default', 'customer') My views.py: class DeviceGroupViewSet(viewsets.ModelViewSet): serializer_class = DeviceGroupSerializer lookup_field = 'customer_uuid' def get_queryset(self): queryset = DeviceGroup.objects.all() customer_uuid = self.request.query_params.get('customer_uuid', None) if customer_uuid is not None: queryset = queryset.filter(customer_uuid=customer_uuid) return queryset What do I need to change so all device groups related to a customer_uuid are returned? -
Receiving "missing FROM-clause" Programming error in django query
I am trying to write a query, that retrieves all subscriptions whose owners should be notified about it's expiry. I would like to exclude the already notified subscriptions and subscriptions that have a newer subscription available. The query is next: Subscription.objects.filter( end_date__gte=timezone.now(), end_date__lte=timezone.now() + timedelta(days=14), ).exclude( Q(notifications__type=Notification.AUTORENEWAL_IN_14) | Q(device__subscriptions__start_date__gt=F('start_date')) ) Without the | Q(device__subscriptions__start_date__gt=F('start_date') part, the query works perfectly. With it, django (postgres) raises the next error: django.db.utils.ProgrammingError: missing FROM-clause entry for table "u1" LINE 1: ...ption" U0 INNER JOIN "orders_subscription" U2 ON (U1."id" = ... I checked the sql and it seems incorrect: SELECT "orders_subscription"."id", "orders_subscription"."months", "orders_subscription"."end_date", "orders_subscription"."start_date", "orders_subscription"."order_id", "orders_subscription"."device_id", FROM "orders_subscription" WHERE ("orders_subscription"."churned" = false AND "orders_subscription"."end_date" >= '2019-04-05T13:27:39.808393+00:00'::timestamptz AND "orders_subscription"."end_date" <= '2019-04-19T13:27:39.808412+00:00'::timestamptz AND NOT (("orders_subscription"."id" IN (SELECT U1."subscription_id" FROM "notifications_notification" U1 WHERE (U1."type" = 'AUTORENEWAL_IN_2W' AND U1."subscription_id" IS NOT NULL)) OR ("orders_subscription"."device_id" IN (SELECT U2."device_id" FROM "orders_subscription" U0 INNER JOIN "orders_subscription" U2 ON (U1."id" = U2."device_id") WHERE (U2."start_date" > (U0."start_date") AND U2."device_id" IS NOT NULL)) AND "orders_subscription"."device_id" IS NOT NULL)))) LIMIT 21 Execution time: 0.030680s [Database: default] This is the part that is causing the issue: INNER JOIN "orders_subscription" U2 ON (U1."id" = U2."device_id") WHERE (U2."start_date" > (U0."start_date") AND U2."device_id" IS NOT NULL)) U1 is not defined … -
How to pass variables from HTML to Django
I have this form in my Django Template and I want to receive the data from a view function how can I do this? <form methods="POST" action="{% url 'pars' %}" name="JsonForm"> <textarea form="JsonForm" name="JsonInput" rows=10 class="form-control col-md-7 col-xs-12"></textarea> <button type="submit" form="JsonForm" class="btn btn-info"> Send Sample</button> </form> and this is my URL: url('^pars',views.UI_pars,name='pars'),