Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show clusters in a map?
I'm building a Flutter map and I want show clusters that are storred in a Django server database. I want to do a similar view as this but instead of showing all the users location, I want to show the surface that these users are occupying (the surface of a cluster). PS: I'm using a package named flutter_map to display the map. -
Save to db only if changing fields
Is there a better way of doing the following in Django: obj = Thing.objects.get(name=name) if obj.a != a or obj.b != b: obj.a = a obj.b = b obj.save() So I wish to save if ether a or b has become invalid and I can’t make any change to the save implementation. And I’d like to stick to using the model instance rather than solving this using a query set. -
Database not updating between tests in Django
I'm trying to run a create test followed by an update, however on the second test I'm unable to find the object created in the first test. I've realised that this is because the object is not added to the DB until after both tests have run. Does anyone know why this is? And how I can run a create test, followed by an update test that uses the object created in the create test? from unittest import TestCase class QuantsTests(TestCase): def setUp(self): self.factory = RequestFactory() def test_create_object(self): object = Object() object.name = "123456789" object.save() def test_update_object(self): Object.objects.filter(name="123456789") Error: object.models.Model.DoesNotExist: Object matching query does not exist. -
Getting 'Invalid request method' error when trying to pass Scrapy data to Django using Python APIs
I have a problem, I created a scrapy project and a django project with an application, I registered the application, set the urls, set the views, and also wrote the spider, but when I go to the localhost stand, I get an error this is my piece of a spider with pandas, I only put the end here because the spider is ok , it saves the data to a json file on the disk, I want to send it to DJANGO code is scrapy data_dict = df.to_dict(orient='records') data = {'data': data_dict} print(df) yield scrapy.Request( url='http://127.0.0.1:8000/receive_data/', method='POST', body=json.dumps(data), headers={'Content-Type': 'application/json'}, callback=self.handle_response, cb_kwargs={'df': df} ) df.to_json('data.json', orient='records', lines=True) def handle_response(self, response, df): if response.status == 200: self.log('Data successfully sent.') else: self.log(f'Data sending failed. Response status: {response.status}') df.to_json('data.json', orient='records', lines=True) my views in Django @csrf_exempt def receive_data(request): if request.method == 'POST': data = json.loads(request.body) toy = modul toy.xx = data.get('xxx') toy.xx = data.get('xxx') toy.xx= data.get('xx') toy.xx = data.get('xx') toy.xx = data.get('xx') if toy.xxx is not None and toy.xxx is not None and toy.xx is not None and toy.xxx is not None and toy.xx is not None: toy.save() response_data = { 'message': 'Data received and saved successfully.', } else: response_data = { 'error': … -
django-oscar / django-oscar-api: huge number of queries to render the ProductSerializer
I am using django-oscar with my own Product class, and a serializer for Django REST Framework. I am finding that adding some properties which are stored as attributes results in a huge number of queries. For example as soon as I add "legacy_title" (which is an attribute I've added) to the serializer's fields, the number of queries made to render this result goes up from 3 to 70. I have 21 products in my databases. from oscarapi.serializers.product import ProductSerializer as CoreProductSerializer class ProductSerializer(CoreProductSerializer): class Meta(CoreProductSerializer.Meta): fields = ( "url", "id", "description", "slug", "upc", "title", "structure", "legacy_title", ) My Product class: from oscar.apps.catalogue.abstract_models import AbstractProduct def attribute_error_as_none(callable_): try: return callable_() except AttributeError: return None class Product(AbstractProduct): @property def legacy_title(self) -> str: return attribute_error_as_none(lambda: self.attr.legacy_title) or self.title I'm using django-oscar-api's built-in ProductList view. If I add a few more fields which are backed by attributes, then the query count keeps going up, to 84 queries for these 21 products. Then add things like children, recommendations, and images, and it takes 240 queries to render this result! How can I get the query count under control? The endpoint to fetch all products is by far the slowest API endpoint in my entire backend … -
how can i make like and unlike button more smooth Using django and javascript in python framework django?
“Like” and “Unlike” buttons with icons Users should be able to click a button or link on any post to toggle whether or not they “like” that post. Using JavaScript asynchronously let the server know to update the like count (as via a call to fetch) and then update the post’s like count displayed on the page, without requiring a reload of the entire page. problem is I cannot toggle between the like and unliked icons when I am in the unlike icon when I like one post liked count goes to all posts. look like my code is beginner code In html file inside Django templates {% if post.id in postLiked %} <button class="btn btn-primary fa fa-thumbs-down" id="{{ post.id }}" onclick="likeOrUnlike('{{ post.id }}', '{{ postLiked }}')"></button> {% else %} <button class="btn btn-primary fa fa-thumbs-up" id="{{ post.id }}" onclick="likeOrUnlike('{{ post.id }}', '{{ postLiked }}')"></button> {% endif %} <div class="container"> <div class="row justify-content-center"> <h3 class="col-4">Like: {{ likes.count }}</h3> </div> </div> In models.py class LikeOrUnlike(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='likeByUser') post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='postLiked') def __str__(self): return f'{self.user} liked this {self.post}' In urls.py path("", views.index, name="index"), path('like/<int:post_id>', views.like,name='like'), path('unlike/<int:post_id>', views.unlike,name='unlike') In views.py def index(request): likes = LikeOrUnlike.objects.all() postLiked = [] try: … -
How can I set the permission policy for a custom Image model in Wagtail?
In a Django/Wagtail project, I use a CustomImage model inheriting from Wagtail's AbstractImage/Image model. When I want to set Image permissions for a new group of users, it doesn't work though, because the function set_permission_policy() from the source file permissions.py takes the original (Wagtail) Image model as an argument auth_model while it should take my CustomImage model (as the users have permissions regarding the CustomImage model): def set_permission_policy(): """Sets the permission policy for the current image model.""" global permission_policy permission_policy = CollectionOwnershipPermissionPolicy( get_image_model(), auth_model=Image, owner_field_name="uploaded_by_user" ) When I experimentally changed the value of auth_model in the source code to my CustomImage model, everything started working, but I need a solution which will be based on modifying my code and not the source Wagtail code. Everytime Wagtail checks permission policy (e.g. in views), it imports directly the wagtail.images.permissions. How to change it in my code so that the permission policy can be set for my CustomImage model and not for the original Wagtail's Image model? -
What can I do to troubleshoot Django's failure to connect to Postgres in Docker-Compose on Ubuntu server?
I am trying to deploy my django app on Ubuntu server. It is actually working on localhost with windows machine. Dockerfile # pull official base image FROM python:3.11.2-slim-buster # set working directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # updated # install system dependencies RUN apt-get update \ && apt-get -y install gcc postgresql \ && apt-get clean # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # new # copy entrypoint.sh RUN apt-get update && apt-get install -y netcat COPY ./entrypoint.sh /usr/src/app/entrypoint.sh RUN chmod +x /usr/src/app/entrypoint.sh # add app COPY . . # new # run entrypoint.sh ENTRYPOINT ["/usr/src/app/entrypoint.sh"] docker-compose version: '3.8' services: qutqaruv: build: ./app command: gunicorn qutqaruv_core.wsgi --bind 0.0.0.0:8001 volumes: - ./app/:/usr/src/app/ - static_volume:/static ports: - "8001:8001" env_file: - ./app/.env.dev depends_on: - qutqaruv-db nginx: image: nginx:1.22.1 ports: - "82:8081" volumes: - ./nginx/nginx-setup.conf:/etc/nginx/conf.d/default.conf:ro - static_volume:/static depends_on: - qutqaruv qutqaruv-db: image: postgres:15 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=qutqaruv - POSTGRES_PASSWORD=qutqaruv - POSTGRES_DB=qutqaruv_dev volumes: postgres_data: static_volume: entrypoint #!/bin/sh if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." while ! nc -z $SQL_HOST $SQL_PORT; do echo $SQL_HOST $SQL_PORT sleep 0.1 echo "Got lost in this process" … -
openpyxl multiple headers and content
I'm using openpyxl for the first time in my django project. I got the task to make a two-part excel, that should be looking approximately like this: So basically i want to shaw all users of a certain organisation. This is what I have so far: def export_organisation(self, org_id): organization = Organization.objects.get(pk=org_id) wb = Workbook() ws = wb.active ws.title = "OKR" headers = [ ['Organisation Name', 'Signup Date', 'Language'], ['First Name', 'Last Name', 'Email'] ] line = 1 # Start from the first row for header_row in headers: ws.append(header_row) # Format bold the cells in the first row ft_bold = Font(bold = True) for cell in ws[ws.max_row]: cell.font = ft_bold line = ws.max_row+1 ws['A' + str(line)] = organization.name ws['B' + str(line)] = organization.signup_date.strftime("%d/%m/%Y") ws['C' + str(line)] = organization.language for user in organization.users.all(): ws['D' + str(line)] = user.first_name ws['E' + str(line)] = user.last_name ws['F' + str(line)] = user.email line+=1 # Filename with team name and date wb.save('{}.xlsx'.format(org_id)) But this gives me following output: Is there a way to make it look like the first image? If yes, what did I miss? -
How to annotate and combine some fields using Django annotate ORM?
I have a product table with 2 fields: Name Tag A 12 B 13 I want to fetch the rows annotating and adding a field type, which is a list , type=[1,2], such that I get the output as: Name Tag Type A 12 1 B 13 1 A 12 2 B 13 2 What should the query be to get the desired result? The query should be Product.objects.annotate(type=?) -
Running tests on Django multitable inheritance model causes IntegrityError
Running tests on Django multitable inheritance model causes IntegrityError Hello, I created a parent class and two children classes like that from django.db import models class A(models.Model): .... class B(A): .... class C(A): .... Whenever I try to run tests that create instance of class B I get this error django.db.utils.IntegrityError: duplicate key value violates unique constraint "app_b_pkey" E DETAIL: Key (a_ptr_id)=(2) already exists. -
Removed a container using command docker rm -f container_name, then when execute docker inspect container_name it returns a json output is it a bug
I removed a container using the following command docker rm -f container_name then when I execute docker inspect container_name i get the json output is it a bug ? When a docker container is removed, and after that a docker inspect is done it should return nothing. -
How to Join on Django Using ORM
Hello everybody I am at my wits' end here, I need help with doing a simple join between 2 tables using DJANGO ORM. The ultimate goal is to return a json response compatible with datatable which contains the product details and product category name instead of the category id. Like this { "draw": 1, "recordsTotal": 1, "recordsFiltered": 1, "data": [ { "productid": 4, "sku": "000001", "shortcode": "CBG", "category": 2, "categoryname": "Burgers", "productname": "Cheese Burger", "description": "This is a cheese burger", "barcode": "000001", "treshhold": 10, "isactive": true } ] } Here are my models class ProductCategory(models.Model): categoryid = models.AutoField(primary_key=True) shortcode = models.CharField(max_length=10) categoryname = models.CharField(max_length=50,unique=True) isactive= models.BooleanField(default=True) class Meta: db_table="tblProductCategory" class Product(models.Model): productid = models.AutoField(primary_key=True) sku = models.CharField(max_length=20,unique=True) shortcode = models.CharField(max_length=10) category = models.ForeignKey(ProductCategory, on_delete=models.SET_DEFAULT,default=0) productname = models.CharField(max_length=50) description = models.CharField(max_length=50) barcode = models.CharField(max_length=20) treshhold = models.IntegerField() isactive= models.BooleanField(default=True) class Meta: db_table="tblProduct" Here is my view def get_product(request): recordsTotal = 0 draw = int(request.GET['draw']) start = int(request.GET['start']) length = int(request.GET['length']) products = Product.objects.filter(sku__icontains = request.GET['sku']).select_related('category') recordsTotal = products.count() recordsFiltered = recordsTotal page = start / length + 1 paginator = Paginator(products, length) try: object_list = paginator.page(page).object_list except PageNotAnInteger: object_list = paginator.page(draw).object_list except EmptyPage: object_list = paginator.page(paginator.num_pages).object_list data = [model_to_dict(product) for product … -
makemigrations-command doesn't do anything
My production django-server uses postgres 12.12, django 32 and python 3.7. My test-server uses the exactly same software, but postgress 12.15. After adding a new table 'etusivu_heroimg' I copied contents of the production postgres into my test postgres database and run python manage.py makemigrations and python manage.py migrate --fake. The table was created and related features worked. Then I checked that the production side had exactly same code as the test server before migration commands, even the app-specific migration-directories were same. But when I ran the migration commands on the production side the new table wansn't created. (pika-env) [django@tkinfra01t pika]python manage.py makemigrations Migrations for 'etusivu': etusivu/migrations/0003_heroimg.py - Create model HeroImg (pika-env) [django@tkinfra01t pika]$ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, conf, contenttypes, core, django_comments, etusivu, generic, kasitesivu, page_types, pages, redirects, sessions, sites Running migrations: No migrations to apply. Your models in app(s): 'admin', 'auth', 'conf', 'contenttypes', 'core', 'django_comments', 'generic', 'page_types', 'pages', 'redirects', 'sessions', 'sites' have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. (pika-env) [django@tkinfra01t pika]python manage.py makemigrations No changes detected However the django_migrations-table was … -
How can I render dynamic QR codes in a slider using Django data?
Help, please I need to render in slider dynamic qr-codes. I receive data from admin model (Django). It work for text, but link for qrs are the same. <div id="carouselExampleIndicators" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-inner"> {% for a in advertising %} <div class="carousel-item carousel-item1 {% if forloop.first %}active{% endif %}" data-bs-interval="2000"> <h3 class="install-app">{{a.advertising_text}}</h3> <div class="qr-wrapper"></div> </div> {% endfor %} </div> </div> And script qrCodeMaker(); function qrCodeMaker(qr) { const qrs = document.querySelectorAll(".qr-wrapper"); console.log('qrs', qrs) qrs.forEach(function (qr) { q = new QRCode(qr, { // {% for a in advertising %} text: "{{a.URL}}", // {% endfor %} colorDark: "#002F43", colorLight: "#F5F7F7" } ) }) } -
django-allauth redirect confirm page
I have an app on DJango. In the login part I have implemented authentication with Microsoft using DJango allatuh. When I press the "sign in" button with microsoft, before redirecting to the microsof, it redirects me to a page where I have to press the "continue" button. I want to remove this second page so that it automatically redirects me to the microsoft page. I have this on my "settings.py" file: SOCIALACCOUNT_PROVIDERS = { 'microsoft': { 'APP': { 'client_id': '', 'secret': '', }, 'SCOPE': ['User.Read'], 'AUTH_PARAMS': { 'prompt': 'select_account', }, 'INIT_PARAMS': { 'prompt': 'select_account', }, 'callback_url': 'https://myapp.test.com/accounts/microsoft/login/callback/', }, } ACCOUNT_EMAIL_VERIFICATION = 'None' ACCOUNT_EMAIL_REQUIRED = False I don't know what to change -
How do I enable email verification for new user in CVAT server?
I am trying to enable email verification for new users that'll be registering on the server. I followed the documentation and added the following options in the "base.py" file. But this doesn't seem to work. # https://github.com/pennersr/django-allauth ACCOUNT_EMAIL_VERIFICATION = 'mandatory' EMAIL_HOST = 'smtp.gmail.com' EMAIL_FROM = '<email>' EMAIL_HOST_USER = '<email>' EMAIL_HOST_PASSWORD = '<password>' EMAIL_PORT = 587 EMAIL_USE_TLS = True ACCOUNT_AUTHENTICATION_METHOD = 'username' ACCOUNT_CONFIRM_EMAIL_ON_GET = True ACCOUNT_EMAIL_REQUIRED = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # set UI url to redirect after a successful e-mail confirmation #changed from '/auth/login' to '/auth/email-confirmation' for email confirmation message ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = '/auth/email-confirmation' ACCOUNT_EMAIL_VERIFICATION_SENT_REDIRECT_URL = '/auth/email-verification-sent' INCORRECT_EMAIL_CONFIRMATION_URL = '/auth/incorrect-email-confirmation' OLD_PASSWORD_FIELD_ENABLED = True Code - https://toscode.gitee.com/wangdong_cn_admin/cvat/blob/master/cvat/settings/base.py Documentation - https://toscode.gitee.com/wangdong_cn_admin/cvat/blob/master/cvat/apps/documentation/installation.md#email-verification -
Django path('challenges/',include(challenges.urls)) NameError: name 'challenges' is not defined
When I comment urlpatterns = [ path('admin/', admin.site.urls), #path('challenges/',include(challenges.urls)) ] it is working fine but for urlpatterns = [ path('admin/', admin.site.urls), path('challenges/',include(challenges.urls)) ] it is throwing an error enter image description here why the error is occurring when I am using urlpatterns = [ path('admin/', admin.site.urls), path('challenges/',include(challenges.urls)) ] -
Problem in adding tags with taggit in Django
class Events(models.Model): user_name = models.TextField() e_url = models.URLField(null=True, blank=True) tags = TaggableManager() def __str__(self) -> str: return self.e_name def create_event(self, value): self.user_name = value['username'] self.e_url = value['url'] self.tags = value['tags'] Tags are not storing. When i store them from admin view its working properly. Bur when i try from my webpage its not working. Here value['tags'] contain string with comma separated tag name e.g. 'python,cpp,django'. My tags table is storing nothing in this case MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' -
django-log-viewer: LOG_VIEWER_FILES_PATTERN
I have 2 types of log files, with various "filenames": filename.log filename.log.1 How to configure this in LOG_VIEWER_FILES_PATTERN? This does not work: LOG_VIEWER_FILES_PATTERN = "*.log??" Note: django-log-viewer version 1.1.7 -
In my autocomplete search bar in django app i want that user always gets the most relevant search when he type his query in search bar
So suppose in my app there is a product name "DispoVan 10ml 21mg" and when user gives its query in search bar as 'DispoVan' it works fine but as he mis spell or do some typo error in search query like "dispo 1" search bar did not suggest him any product. i want that if user searches for any product and even if he do some typing error in the name of the product he should get the relevant product. even is there is a space in the search query,any relevant matches should be shown to him. This is my view which is showing list of all the products which matches to search. def search_address(request): address = request.GET.get('query') payload = [] print(address) if address: prod = Product.objects.filter(Q(name__icontains=address)).values_list('name',flat=True) for prod in prod: payload.append(prod) return JsonResponse({'status':200, 'data':payload}) -
What causes 'Broken pipe' errors in a Django application on GKE, and how can I prevent them?
I have deployed a Django application on a Google Kubernetes Engine (GKE) cluster, and it has been functioning well. However, recently I encountered a "Broken pipe" error with the message "Broken pipe from ('35.191.194.192', 57892)" in my application logs. Notably, I did not release any updates during this time, and there were no indications of a broken error in the load balancer logs. and , the error disappeared after some days, even though no new updates were deployed. I would like to understand the root cause behind this issue and learn how to prevent it from occurring in the future. I did not take any specific action to address the issue since it resolved itself after some days. However, I expected to understand the cause of the "Broken pipe" error and find ways to avoid it in the future. -
Got "token": [ "Ensure this field has no more than 500 characters." ] in drf social oauth2
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'drf_social_oauth2.authentication.SocialAuthentication', ), } AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', # drf-social-oauth2 'drf_social_oauth2.backends.DjangoOAuth2', # Django 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'my key' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'my secrect' # Define SOCIAL_AUTH_FACEBOOK_SCOPE to get extra permissions from Facebook. # Email is not sent by default, to get it, you must request the email permission. SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', ] I am using drf-social-oauth2 for Google login. After getting a Google credential from React site. i tried to use 'curl -X POST -d "grant_type=convert_token&client_id=<django-oauth-generated-client_id>&client_secret=<django-oauth-generated-client_secret>&backend=google-oauth2&token=<google_token>" http://localhost:8000/auth/convert-token' But I got "token": ["Ensure this field has no more than 500 characters."] -
How can I fix the 'zsh: command not found' error when trying to set up PostgreSQL for my Django project?
I am on the django official tutorial trying to set up PostgressSQL as the database for my project.I run the command CREATE DATABASE database_name I am getting the error message zsh: command not found. What have I tried so far: It instructs me to install the appropriate database bindings which I believe is psycopg2. I have installed psycopg2. After that it tells me to replace the engine and name values which I have done so substituting the blank strings for values. I don't think I am supposed to share my password or database name so I left it blank. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '', 'USER': '', 'PASSWORD':'', 'HOST': 'localhost', 'PORT': '5432', # default PostgreSQL port } } I went ahead and replaced the engine and name values as they told me. So I am wondering why It acts like I do not have postgress installed when I ran the installer and pgadmin and sucessfuly set it up. A programmer more experienced than myself was able to create a project without fail. Link to django tutorial here: https://docs.djangoproject.com/en/4.2/intro/tutorial02/. What have I tried already, and what steps have I taken to solve the problem: I have tried researching … -
django uwsgi: Server Error (500) - while accessing view model without "q" parameter
I started facing an issue since upgrading my server from Ubuntu 18.04 LTS to Ubuntu 20.04 LTS. It seems that I'm encountering an issue (Server Error (500)) with only one model, specifically with the URI /admin/mymodule/mymodel/. Please refer uwsgi logs below: [pid: 27771|app: 0|req: 4/8] 192.168.1.101 () {72 vars in 1623 bytes} [Fri May 26 06:11:11 2023] GET /admin/mymodule/mymodel/ => generated 145 bytes in 210 msecs (HTTP/1.1 500) 6 headers in 184 bytes (1 switches on core 0) But when trying the same URI with query parameter (/admin/mymodule/mymodel/?all=&q=2022-12-19), it is working fine. Please refer uwsgi logs below: [pid: 27768|app: 0|req: 3/9] 192.168.1.101 () {70 vars in 1627 bytes} [Fri May 26 06:11:15 2023] GET /admin/mymodule/mymodel/?all=&q=2022-12-19 => generated 100205 bytes in 1013 msecs (HTTP/1.1 200) 9 headers in 463 bytes (1 switches on core 0) [pid: 27770|app: 0|req: 3/10] 192.168.1.101 () {68 vars in 1468 bytes} [Fri May 26 06:11:16 2023] GET /admin/jsi18n/ => generated 3187 bytes in 12 msecs (HTTP/1.1 200) 6 headers in 189 bytes (1 switches on core 0) I don't understand the behavior as I'm able to access all other view models and custom views successfully without any issues. And able to access this view with any …