Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to extract Django AutoSlugField output
I am using django-extensions.AutoSlugField and django.db.models.ImageField. To customize image name uploaded for django.db.models.ImageField, what I did: from django.utils.text import slugify # idea is to make image name the same as the automatically generated slug, however don't work def update_image_name(instance, filename): # this debug instance, and instance.slug is empty string print(instance.__dict__) # I attempt to use slugify directly and see that it's not the same as the output generated by AutoSlugField # E.g. If I create display_name "shawn" 2nd time, AutoSlugField will return "shawn-2", but slugify(display_name) return "shawn" print(slugify(instance.display_name)) return f"images/{instance.slug}.jpg" class Object(models.Model): ... display_name = models.TextField() ... # to customize uploaded image name image = models.ImageField(blank=True, upload_to=update_image_name) ... # create slug automatically from display_name slug = AutoSlugField(blank=True, populate_from=["display_name"] Based on what I debug, when I call instance inside update_image_name, slug is empty string. If I understand correctly slug is only created at event save, so when I call ImageField instance, slug is not yet created, therefore empty string. I think it might have something to do with event post save. However, I am not sure if that's the real reason or how to do that. How can I get the automatically generated slug as my customized image name? -
Static file images Not found Django
I'm making a website and the static files are not loading, when i try to accsess static files with localhost:8000/static/image.png it shows this: Page Not found (404)'image.png' could not be found and the index page is showing the image that displays when the image couldn't be found files: VoicesOnTheSpectrum VoicesOnTheSpectrum __pycache__ __init__.py asgi.py settings.py urls.py wsgi.py vots __pycache__ migrations static image.png logo.png style.css votstop.png templates vots base.html index.html __init__.py admin.py apps.py models.py tests.py urls.py views.py db.sqlite3 manage.py settings.py: """ Django settings for VoicesOnTheSpectrum project. Generated by 'django-admin startproject' using Django 3.1.6. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, "vots", "templates") # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '08fqvs#$(dg5t^$75kpyrjv(s-)gv7d(crgmxcl^p7*&jtwbhc' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', … -
FileNotFoundError in Heroku at deploying (Django)
When I run python manage.py collectstatic --noinput in my local machine, it works fine. But when heroku runs python manage.py collectstatic --noinput it gives error like this: for entry in os.scandir(path) FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_5d05d870/static' Please help me. I stucked for 7-8 hours and now it makes my health condition horrible. My project directory seems like this: mysite-----|libooki(app)----------|migrations |----------------------|init.py |----------------------|admin.py |----------------------|........ -----------|media -----------|media_cdn -----------|mysite -----------|static|--------------|css|------style.css -----------|staticfiles -----------|templates -----------|......... My settings.py seems like this. (I followed this article: https://devcenter.heroku.com/articles/django-assets) from pathlib import Path import os import django_heroku BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') INSTALLED_APPS = [ ........, 'libooki', ] MIDDLEWARE = [ ..........................................., 'whitenoise.middleware.WhiteNoiseMiddleware', ] WSGI_APPLICATION = 'mysite.wsgi.application' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) MEDIA_ROOT = os.path.join(BASE_DIR,'media_cdn') MEDIA_URL = '/media/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' django_heroku.settings(locals()) -
Run test but add data to real database
I write some test for my app in Django. as I know when tests run Django create a test database from default database and work with the test database. I used factory boy to generate fake data for the better test but when I run tests factory boy inserts to default database instead of the test database. anyone have an idea about this problem? -
Get non-translated field django-translations
I am trying to get non-translated field texts but I can't as I can not use .translate() to get the default value as the translation does not exists. I am using django-translations and it gives me translated results based on: The active language is a language which is automatically activated in each request. It is usually determined by the Accept-Language header received in each HTTP request (from the browser or another client). You can access it in Django using the get_language() function. Even if I try to use it's context features, as there is no such language as default language to retrieve, I am unable to get non-translated forms of those fields. My model: from translations.models import Translatable class Category(Translatable): name = models.CharField(verbose_name="Category",max_length=150) url_name = models.CharField(verbose_name="URL name",max_length=150) slug = models.SlugField(unique=True, editable=False, max_length=180) def __str__(self): return self.name class Meta: ordering = ['-id'] class TranslatableMeta: fields = ["name"] -
Fetch method put give "SyntaxError: Unexpected end of JSON input"
I state that the script works: successfully changes the correct field to the correct value. Despite this I get this error "SyntaxError: Unexpected end of JSON input". This is the client-side js code. The function gets ad 'id' , the field to change and the value : function mark(id,field,yesno){ fetch('/emails/'+id,{ method : 'PUT', headers: {'Content-Type': 'application/json'}, body : JSON.stringify({ [field]:yesno }) }) .then(response =>response.json()) .catch(error => {console.log('Error while processing the request:' , error)}) } The piece of code on the views.py ... elif request.method == "PUT": data = json.loads(request.body) if data.get("read") is not None: email.read = data["read"] if data.get("archived") is not None: email.archived = data["archived"] email.save() return HttpResponse(status=204) ... And the models.py class Email(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="emails") sender = models.ForeignKey("User", on_delete=models.PROTECT, related_name="emails_sent") recipients = models.ManyToManyField("User", related_name="emails_received") subject = models.CharField(max_length=255) body = models.TextField(blank=True) timestamp = models.DateTimeField(auto_now_add=True) read = models.BooleanField(default=False) archived = models.BooleanField(default=False) def serialize(self): return { "id": self.id, "sender": self.sender.email, "recipients": [user.email for user in self.recipients.all()], "subject": self.subject, "body": self.body, "timestamp": self.timestamp.strftime("%b %d %Y, %I:%M %p"), "read": self.read, "archived": self.archived } -
DRF model relationship serializer with an already populated model
I have a couple models, one of which is already populated with data (book name/ chapter number/ paragraph number data), and I would like to be able to add a note per each unique book name/ chapter number/ paragraph number, but I have been stack for a couple of days. Here are my models: Book model that is already populated with data. from django.db import models class Book(models.Model): day = models.CharField(max_length=128) book = models.CharField(max_length=128) chapter = models.CharField(max_length=256) paragraph = models.CharField(max_length=256) text = models.TextField() link = models.CharField(max_length=256) def __str__(self): return f'{self.book}_{self.chapter}.{self.paragraph} ' class Meta: ordering = ['-id'] verbose_name = "Paragraph" verbose_name_plural = "Paragraph" And here is an example data that this model has / returns (list of objects - object example below): { "id": 25, "day": "2", "book": "Some book", "chapter": "1", "paragraph": "3", "text": "This is an example text that the user would like to attach a note to", "link": "https://somelink.com" } Day here refers to a schooling day, and each day contains a number of paragraphs that need to be read / noted per day (for example day 1 returns 10 objects - paragraphs - as the above ) Here is the Note model that should store the current … -
Implementing 5-STAR rating system in my app
I am implementing a 5-star rating system in my application but got the error that when I click on RATE THIS PRODUCT button it shows me the whole html of rate.html in the URL.I goolge it but I do not have any clue why?. This is my last option my models.py is: class Review(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product , on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) text = models.TextField(max_length=3000 , blank=True) rate = models.PositiveSmallIntegerField(choices=RATE_CHOICES) likes= models.PositiveIntegerField(default=0) dislikes = models.PositiveIntegerField(default=0) def __str__(self): return self.user.full_name my views.py is: def Rate(request , slug): product = Product.objects.get(slug=slug) user = request.user if request.method == 'POST': form = RateForm(request.POST) if form.is_valid(): rate = form.save(commit=False) rate.user = user rate.product = product rate.save() return HttpResponseRedirect(reverse('detail', args=[slug])) else: form = RateForm() template = loader.get_template('rate.html') context = { 'form':form, 'product':product, } return HttpResponseRedirect(template.render(context, request)) my urls.py is: path('<slug:slug>/rate/', Rate, name='rate-product'), In my product detail I gave the link of rate the html like this: <h3>Rate this product</h3><a href="{% url 'products:rate-product' object_list.slug %}">Rate this product</a> and my rate.html is: {% extends "base.html"%} {% block content %} <form method="post" action="" role="form" class="col s12"> {% csrf_token %} <div class="input-field col s12"> {{ form.rate }} </div> <div class="input-field col s12"> {{ form.text }} <label … -
How do you start the development server when starting a new Django project
I have been trying to start a new Django project for the first time and I can't seem to figure out how to run the server. On the tutorial page for Django it says Change into the outer mysite directory, if you haven’t already, and run the following commands: ...\> py manage.py runserver When I do this, nothing happens. I tried running the command from the mysite directory and from the Django test folder I made for the project. Here is a screen shot screenshot of cmd terminal The Django tutorial says I should be expecting this result: Performing system checks... System check identified no issues (0 silenced). You have unapplied migrations; your app may not work properly until they are applied. Run 'python manage.py migrate' to apply them. February 19, 2021 - 15:50:53 Django version 3.1, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Before I did this I installed pipenv by following this guide and followed the guide all the way up to "Next Steps". I have also attached a screen shot of what the folder looks like: Picture of Django project folder What am I doing wrong? -
Django Postgres - What is the best way to add 50 millions products to a project
We have a project. Django + Postgres. At the moment we have 5 millions products in the database. Now we want to add 10 more product categories to our website. This 10 new categories will have about 50 millions products. What is the best way to do it. First I wanted to create a subdomain for each category. For example: - clothes.site.com - home.site.com - pc.site.com and so on... But now I think it's not the best solution. It would be better to have everything inside the main domain. Like site.com/clothes/ site.com/home/ site.com/pc/ But what is the best way to do it? I would be very grateful for your help. -
django-imagekit thumbnail serializer for Django Rest Framework + extra
guys. I spent some time figuring out how can I use django-imagekit with DRF without defining ImageSpecField fields in model (a large number of thumbnail types make model dirty). from collections import OrderedDict from rest_framework import serializers from imagekit.cachefiles import ImageCacheFile class ThumbnailField(serializers.ImageField): def __init__(self, spec, **kwargs): self.spec = spec super().__init__(**kwargs) def to_representation(self, original_image): if not original_image: return None cached = ImageCacheFile(self.spec(original_image)) cached.generate() return super().to_representation(cached) class ImageKitField(serializers.ImageField): def __init__(self, **kwargs): self.specs = kwargs.pop('specs', {}) self.full = kwargs.pop('full', False) super().__init__(**kwargs) def to_representation(self, original_image): if not original_image: return None result = OrderedDict() for field_name, spec in self.specs.items(): cached = ImageCacheFile(spec(original_image)) cached.generate() result[field_name] = super().to_representation(cached) if self.full: result['full'] = super().to_representation(original_image) return result Using ThumbnailField return just image thumb url. You can also use source and other ImageField params like so: class UserSerializer(serializers.ModelSerializer): thumb = ThumbnailField(spec=UserThumbnailSpec, source='image') Result: { "thumb": "http://example.com/.../thumb.jpg" } ImageKitField is extra field which group multiple thumbnail dimensions together. full is optional flag that include original image to result dict. class UserSerializer(serializers.ModelSerializer): image = ThumbnailField(specs={ 'small': SmallThumbnailSpec, 'large': LargeThumbnailSpec, }, full=True) Result: { "image": { "small": "http://example.com/.../small.jpg", "large": "http://example.com/.../large.jpg", "full": "http://example.com/.../full.jpg", } } Enjoy! -
Django and GOOGLE_APPLICATION_CREDENTIALS access
I'm trying to implements some google cloud funcions via Django, but I can't figure out how to use GOOGLE_APPLICATION_CREDENTIALS which is envirnomental variable. WIth a python local script it works, but when I try to run the same function in Django it doesn't work, and looks like the Django doesn't see this variable. Please help to solve this. Thanks -
How to create dropdown box with forms.ModelForm in Django?
I'm trying to add a dropdown box of choices in my form. What I tried: from django import forms from .models import Car class CarForm(forms.ModelForm): owner_name = forms.CharField(max_length=100, label='Owner Name', required=True) car_type = forms.ChoiceField(choices=Car.CarTypes.choices, label='Car Type', required=True) class Meta: model = Car fields = ('owner_name', 'car_type') It adds the car_type field to the form but it's not a dropdown for some reason (it's a regular empty box you could fill). The CarTypes looks like: class CarTypes(models.TextChoices): X = 'some_x' Y = 'somy_y' # ... What could be the reason? In my Car class I have: car_type = models.CharField(max_length=24, choices=CarType.choices, default=CarType.X). Could be it? I think CharField makes it empty box. But changing it to ChoiceField ends with: module 'django.db.models' has no attribute 'ChoiceField'. How to solve it? I tried this approach but it uses a tuple instead of a class. -
Debugging GraphQL / graphene database queries in Django
Debugging database queries in Django is commonly done with the Django Debug Toolbar or similar middlewares. However when using Graphene / GraphQL, these queries are not captured. Is there a method to view these queries apart from logging all queries? I am running an ASGI where the some code paths are logged (Django admin, user authentication) but not those from Graphene. Could this be related to https://github.com/jazzband/django-debug-toolbar/issues/1430 ? For my use case in particular I want to analyze GraphQL queries. However for the following query these are the logged queries. The request returns a number of entries. { allPeripheralComponents { edges { node { id siteEntity{ name } peripheralType dataPointTypeSet{ edges{ node{ id name unit } } } } } } } -
How can I do to customize my Django Activation account email?
I am working on activation account I put the correct credentials : EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = '' EMAIL_HOST_PASSWORD = '' EMAIL_HOST_USER = '' EMAIL_PORT = '' I received the following mails : For the subject : Activate your account on localhost:8000 And for the body : localhost:8000 Hello user4! Please activate your account on the link: http://localhost:8000/activate/eyJ1c2VybmFtZSI6InJvbWFyaWM5MSIsImFjdGlvbiI6ImFjdGl2YXRpb24ifQ:1lDme0:teqKv8gEfAp59y0UAJm8mCq0-mSRXIxTZsEQ1a8V0aE I don't know how can I do to customize this emails. Do you have any ideas to do that ? Thank oyu very much ! -
Django create subquery with values for last n days
I am using Django 3.1 with Postgres, and this is my abridged model: class PlayerSeasonReport: player = models.ForeignKey(Player) competition_season = models.ForeignKey(CompetitionSeason) class PlayerPrice: player_season_report = models.ForeignKey(PlayerSeasonReport) price = models.IntegerField() date = models.DateTimeField() # unique on (price, date) I'm querying on the PlayerSeasonReport to get aggregate information about all players, in particular I would like the prices for the last n records (so the last price, the 7th-to-last price, etc.) I currently get the PlayerSeasonReport queryset and annotate it like this: base_query = PlayerSeasonReport.objects.filter(competition_season_id=id) # This works fine last_value = base_query.filter( pk=OuterRef('pk'), ).order_by( 'pk', '-player_prices__date' ).distinct('pk').annotate( value=F('player_prices__price') ) # Pull the value from a week ago # This produces a value but is logically incorrect # I am interested in the 7th-to-last value, not really from a week ago from day of query week_ago = datetime.datetime.now() - datetime.timedelta(7) value_7d_ago = base_query.filter( pk=OuterRef('pk'), player_prices__date__gte=week_ago, ).order_by( 'pk', 'fantasy_player_prices__date' ).distinct('pk').annotate( value=F('player_prices__price') ) return base_query.annotate( value=Subquery( value.values('value'), output_field=FloatField() ), # Same for value_7d_ago # ... # Many other annotations ) Getting the most recent value works fine, but getting the last n values doesn't. I shouldn't be using datetime concepts in my logic, since what I'm really interested in is in the n-to-last values. I've … -
Problem in rendering the data from Postgres in Django views.py from two different models
I am created an app name order whose models field look like this:- from django.db import models from ckeditor.fields import RichTextField from datetime import datetime # Create your models here. class create_order(models.Model): emb_choice=( ('Yes', 'Yes'), ('No', 'No'), ('Other', 'Other'), ) wash_choice=( ('Yes', 'Yes'), ('No', 'No'), ('Other', 'Other'), ) tape_choice=( ('Yes', 'Yes'), ('No', 'No'), ('Other', 'Other'), ) x=datetime.now() month_code_choice=( ('1-{}'.format(x.year), '1-{}'.format(x.year)), ('2-{}'.format(x.year), '2-{}'.format(x.year)), ('3-{}'.format(x.year), '3-{}'.format(x.year)), ('4-{}'.format(x.year), '4-{}'.format(x.year)), ('5-{}'.format(x.year), '5-{}'.format(x.year)), ('6-{}'.format(x.year), '6-{}'.format(x.year)), ('7-{}'.format(x.year), '7-{}'.format(x.year)), ('8-{}'.format(x.year), '8-{}'.format(x.year)), ('9-{}'.format(x.year), '9-{}'.format(x.year)), ('10-{}'.format(x.year), '10-{}'.format(x.year)), ('11-{}'.format(x.year), '11-{}'.format(x.year)), ('12-{}'.format(x.year), '12-{}'.format(x.year)), ) merchant_name=models.CharField(max_length=255) sample_type=models.CharField(max_length=255) buyer_name=models.CharField(max_length=255) style_type=models.CharField(max_length=255) fabric_type=models.CharField(max_length=255) fabric_article=models.CharField(max_length=255) emb=models.CharField(choices=emb_choice, max_length=255) wash=models.CharField(choices=wash_choice, max_length=255) tape=models.CharField(choices=tape_choice, max_length=255) description=RichTextField(blank=True) in_house=models.DateField(default=datetime.now) new_in_house=models.DateField(default=datetime.now) delivery_date=models.DateField() month_code=models.CharField(choices=month_code_choice, max_length=255) qty_of_order=models.IntegerField() bal_to_load=models.IntegerField() created_at=models.DateField(editable=False,auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) Now I created another app called "wherehouse". Whose models look like this:- from django.db import models from django.db.models.deletion import SET_NULL from ckeditor.fields import RichTextField from datetime import datetime from order.models import create_order # Create your models here. class wherehouse_model(models.Model): status_choice=( ('Confirm', 'Confirm'), ('Reject', 'Reject'), ) product_id=models.OneToOneField(create_order, primary_key=True, on_delete=models.CASCADE) description=RichTextField(blank=True) status=models.CharField(choices=status_choice, max_length=255) def __str__(self): return str(self.product_id) In this model I try to store the status of all the product which is created using "create_order" model.Now what happen this "wherehouse" app user confirming the product whether it is available or not. If he … -
Decreasing pipeline execution time for python testing phase
Appreciate your support as I need to decrease the pipeline execution time for running python test cases It takes 3 minutes or less via my local machine but 8 minutes or more via pipeline machine Local machine processor Intel(R) Core(TM) i7-4510U CPU @ 2.00GHz memory 16GiB System Memory Cloudbuild Pipeline machine 8 vCPUs 8 Gib RAM I used the below commands to execute the test cases but it is not different so I think that the test workers do not work parallel, The 8 cpu cores is not used well or docker-compose step is not used pipeline machine full capabilities. pytest -n 4 pytest -n 6 pytest -n auto my docker-compose file version: '3' services: redis: image: registry.hub.docker.com/library/redis:latest expose: - 6379 postgres: image: registry.hub.docker.com/library/postgres:9.6 restart: always command: -c max_connections=3000 -c fsync=off -c synchronous_commit=off -c full_page_writes=off -c max_locks_per_transaction=500 volumes: - ./postgres/pgdata:/var/lib/postgresql/data environment: - POSTGRES_PASSWORD=my-postgres-pass - POSTGRES_USER=my-postgres-user - POSTGRES_DB=my-postgres-db expose: - "5432" datastore: image: registry.hub.docker.com/google/cloud-sdk entrypoint: bash command: gcloud beta emulators datastore start --host-port 0.0.0.0:8081 environment: - CLOUDSDK_CORE_PROJECT=my-project expose: - "8081" pubsub: image: registry.hub.docker.com/google/cloud-sdk entrypoint: bash command: gcloud beta emulators pubsub start --host-port 0.0.0.0:8085 environment: - CLOUDSDK_CORE_PROJECT=my-project expose: - "8085" django: working_dir: /opt/my-project image: $GUNICORN_IMAGE_NAME entrypoint: bash command: > -c " /usr/local/bin/pip … -
Efficient ways of removing duplicate from a queryset?
I have a table called Clue which has a foreignkey relation with another entity called Entry. class Entry(models.Model): entry_text = models.CharField(max_length=50, unique=True) ..... class Clue(models.Model): entry = models.ForeignKey(Entry, on_delete=models.CASCADE) ...... Now, let's say I have the following queryset clues = Clue.objects.filter(clue_text=clue.clue_text) which returns something like this- [<Clue: ATREST-Still>, <Clue: ATREST-Still>, <Clue: ATREST-Still>, <Clue: YET-Still>, <Clue: YET-Still>, <Clue: SILENT-Still>] As, you can see there are different clue objects but some of them are tied to the same entry objects. I tried the following:- clues = Clue.objects.filter(clue_text=clue.clue_text).distinct() But this won't work as the field repeating is a foreign key value. Correct me if I am wrong. Essentially, I want my queryset to look something like this [<Clue: ATREST-Still>, <Clue: YET-Still>, <Clue: SILENT-Still>] I was able to achieve it through the following but I was looking at a solution that can be done at the database level rather than doing it in memory. This is my approach clue_objs=[] temp = {} clues = Clue.objects.filter(clue_text=clue.clue_text) for clue in clues: if not temp.get(clue.entry.entry_text): temp[clue.entry.entry_text]=1 clue_objs.append(clue) -
Django not getting installed
I tried to install django this message comes when i tried it in cmd. None of the basic commands are executing after creating the environment [1]: https://i.stack.imgur.com/VDxe7.png whereas in my text editor it doesnt show any message as well as doesn't execute. I tried installing directx for this missing file but it still didnt work Help me! -
What defines iterator name in for loop template tag?
In Django docs about templates, there is example of for loop tag, that iterates trought elements of athlete_list, but I can't find any information about what is athlete_list and where is from. I don't know what defines name of athlete_list iterator. <ul> {% for athlete in athlete_list %} <li>{{ athlete.name }}</li> {% endfor %} </ul> -
Django: Picking from QuerySet without slicing it
I have in essential the following models in Django: class Group(models.Model): class People(models.Model): groups = models.ManyToManyField(Group, related_name='members') class Cars(models.Model): groups = models.ManyToManyField(Group, related_name='vehicles') I want to choose a certain predefined amount of people and cars from some groups. The groups and the corresponding proportions I have saved in lists: groups = [ some groups ] proportion_pps = [ some positive integer list ] proportion_cars = [ some positive integer list ] Now the code for my choosing looks like so: for x, group in enumerate(groups): pps |= People.objects.filter(groups=grop).all().order_by('?')#[:proportion_pps[x - 1]] crs |= Cars.objects.filter(groups=group).all().order_by('?')#[:proportion_crs[x - 1]] So far so good... But now I run into a "slicing" error when I try: pps.distinct() crs.distinct() or something like: list_pps = list(pps.values_list('id', flat=True).order_by('?')) I see no way around it. Any help would be appreciated... Thx! -
Django views function without return value
I want to send information back-end via JS to update the database based on user response, but I don't need a JSON response or other HTTP rendering done. It's a test type app so all I'm sending back is a single identifier (integer) and boolean value to indicate pass/fail on their response. Currently I am using a fetch(url/${identifier}/bool) and all works as intended with the data management, but Python/Django throws an error as I am not returning any value. So I have two questions. Is fetch the right way of doing this as I am not actually expecting a response and I am doing no manipulation JS side with the data after calling it. How can I stop Django from expecting a response on this as I intend to run the call as a simple function rather than an API call with JSON response sent back. Thank you for the help. -
Gunicorn started with systemd or Gunicorn started docker
I'm hosting a number off small Django applications on a VM in the cloud. The number of applications keeps growing so I need to figure out a small hosting setup. I want to share the NGINX, Redis, Postgress on 1 host and host the different applications under there. There are 2 option : Host every Django on systemd controlled Unicorn Instance using venv.. Host Every Django in a container to host the different Unicorn Instances. Both should be used and the unix sock connection. Any experience anybody ? -
How show Many2Many inLines in admin
I have models: class PostLike(Base): like_from = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='like_from', verbose_name=_("like from")) like_to = models.ForeignKey('Post', on_delete=models.CASCADE, related_name='like_to', verbose_name=_("like to")) and class Post(Base): likes = models.ManyToManyField(PostLike, related_name='post_likes', verbose_name=_("likes"), blank=True) How can I show in admin InLine likes in Post model?