Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django query not respecting order for ltree field subquery (Postgresql)
Background I have an application that uses a team model that includes a field using the ltree postgres extension, which is a field that allows you to store the entire ancestral chain of an object including itself in a single field (the representation I see is . separated id values). This field type is not supported by Django out of the box, so some custom extensions were added to add proper support for the ancestor/descendant checks that I think are based on some packages available that do some of the same. This ltree field is being used as a path column in our Team table in the database to store team hierarchies. The Problem There is an export option that will generate a CSV copy of the team structure, and as part of that, a given team will have the ancestors display each in their own columns next to other information about the team. When some larger teams are exported, the order of the ancestors is scrambled. Some digging shows that the subquery used to create the list annotation that explodes the path into individual teams is not respecting the ordering provided in the subquery. The basic query that is … -
How can I change the label for a field in model serailizers
I have my model with Django ORM: class MyModel(): contract_version = models.ForeignKey( ContractVersion, verbose_name='Contract', related_name='contract_versions', on_delete=models.PROTECT, ) I also have serializers: class ContractSerializer(ModelSerializer): class Meta: model = Contract fields = ( ... ) inlines = ( 'contracts_versions', ) How can I change the label in this case? Without changing the model, this is needed for the OPTIONS of my query. P.S. I do not need to add this field to the fields -
What is & How to know the default screenshot's window size of browsers in Selenium?
I ran the code below to take 3 screenshots of Django Admin on Google Chrome, Microsoft Edge and Firefox. *I use Django, pytest-django and Selenium: import os import pytest from selenium import webdriver def take_screenshot(driver, name): # time.sleep(1) os.makedirs(os.path.join("screenshot", os.path.dirname(name)), exist_ok=True) driver.save_screenshot(os.path.join("screenshot", name)) @pytest.fixture(params=["chrome", "edge", "firefox"], scope="class") def driver_init(request): if request.param == "chrome": web_driver = webdriver.Chrome() request.cls.browser = "chrome" if request.param == "edge": web_driver = webdriver.Edge() request.cls.browser = "edge" if request.param == "firefox": web_driver = webdriver.Firefox() request.cls.browser = "firefox" request.cls.driver = web_driver yield web_driver.close() @pytest.mark.usefixtures("driver_init") class Screenshot: def screenshot_admin(self, live_server): self.driver.get(("%s%s" % (live_server.url, "/admin/"))) take_screenshot(self.driver, "admin/" + self.browser + ".png") Then, I could take 3 screenshots which have different window size depending on browsers as shown below: chrome.png: edge.png: firefox.png: So, what is & how can I know the default screenshot's window size of the browsers in Selenium? -
Session cookie for multiple domains. Security concerns
I think this is kind of a trivial question, but I got an idea that I want to share and ask if it is even necessary. I have 3 react apps as 3 different subdomains - auth.site.com, client.site.com and admin.site.com, and a django backend at api.site.com. Now it works like this: User logins from auth, through api.site.com Django sets session cookie with Domain=.site.com User is redirected to the allowed react app (client or admin) But... This way I can't set the cookie to specific react app subdomain, because Set-Cookie header is sent from api and browser rejects it if domain is not .site.com Second approach: User logins at auth User is redirected to, for example admin.site.com/internal/setcookie/<long_long_token> (web server sends these /internal/* paths to django instead of react) At that view, django gets the session from this one-time <long_long_token>, and sets the cookie with Domain=admin.site.com. User is redirected to / Considerations First of all, I wonder if can I even use this, will the browser not send cookies to api.site.com when session cookie has a Domain=admin.site.com? Also, I don't like that if user logins and is redirected to client, he can still just change subdomain to admin and will still have … -
How to know if a 500 error is raised in DRF exception handler?
I am creating a custom exception handler in django rest. I want to determine if incoming exception is a 500 exception or related to 500 exceptions. from rest_framework.views import exception_handler def custom_exception_handler(exc, context): response = exception_handler(exc, context) if response is not None: response.data['status_code'] = response.status_code return response The problem is response status code is determined only when exception is related to serializer or a explicit response with 500 error code is raised. When I try to raise a python exception like ValueError, the response is None. And there is no way to know if exception is 500 or should be 500. I need to know if exception is a 500 error in my custom exception handler. What should I do? -
What is the best way to split/ set Django Apps for a deep learning application?
I'm working on a deep learning project mainly a sequence to sequence model using Transformers. Required to use Django. Question is: What is the best practice for strcutring such project? Regarding Apps splitting in Dgajno mainly My current structure (Which I feel is very complicated) is: MainApp, App for data_preprocessing, app for deep_learning includes: Seq2SeqProject | |_main_app |_deep_learning_app | |_deep_learning_models (encoder/decoder) | |_utils (config files for deep learning) | |_helpers_function |_Image_preprocessing_app | |_data_fetch | |_data_preprocess | |_data_augmentation Please propose a Apps structure to be readable and easy to track. -
Django Admin: show multiple apps together in one section?
I'm working on a Django API for a webshop, and I organized the models and views into different apps: one for orders, one for baskets, one for products, and one for offers. Now I want to add these models to the admin site, but I don't want it to show up as four different sections each with one model to manage. Instead I want a new "Shop" section where I show the models for all these apps. So instead of this: I want both models in one common section. Is this possible? I tried setting the same verbose name in both app's apps.py file, but that just results in two sections with the same name: -
How to resolve an environment error related to python, which throws an exception of permission denied in installation of packages (Django)?
I have been trying to install django in pycharm, by the command 'pip install django', but somehow it is throwing some environment error which denies the permession to install the packages required for django, like tzdata, sqlparse, site packages. This is the attached screenshot of the exact error to explain my problem in a better way.(https://i.stack.imgur.com/OtT4O.png) I tried changing the permission of all the folders, and gave acces of full control in the properties section of all the folders and files, yet the problem hasn't been resolved. I even tried removing the firewall which might be a problem and might not give permission for the same, but it didn't do anything either. -
Wagtail image search works intermittently
I'm working on a website built using Wagtail CMS. Sometimes, a search for images doesn't return anything even when an image that should match the search term is present. An example is in the screenshots below. There's an image titled "wallpaperflare.com_wallpaper3", but searching for part or all of this title doesn't find the image. The wallpaperflare.com_wallpaper3 image in the CMS The result of searching for the wallpaperflare.com_wallpaper3 image Other times, the search returns the images it's expected to. The result of searching for an image titled "White House" As far as I know, the site uses Wagtail's default images page and search functionality without any modifications. After looking at Wagtail's source code it seems that images should be searchable by their title by default. Also, if it makes any difference, the images are stored in S3. Does anyone know why the image search isn't working properly, and anything I could try to fix it? I've tried checking the settings.py file to see if the search settings aren't set correctly. But, they are set correctly with the code snippet below: WAGTAILSEARCH_BACKENDS = { "default": { "BACKEND": "wagtail.search.backends.database", "AUTO_UPDATE": True, } } -
Failed to find attribute 'application' in 'DierenWelzijn.wsgi'
I try to dockerize django application. And I am using nginx and docker-compose. I can build the images. But if I try to run the docker container. I get this error: [2023-09-11 12:10:55 +0000] [7] [INFO] Booting worker with pid: 7 dwl_backend_rachid-web-1 | 'dockerdierenwelzijn.azurewebsites.net' dwl_backend_rachid-web-1 | Failed to find attribute 'application' in 'DierenWelzijn.wsgi'. dwl_backend_rachid-web-1 | [2023-09-11 12:10:55 +0000] [7] [INFO] Worker exiting (pid: 7) dwl_backend_rachid-web-1 | [2023-09-11 12:10:55 +0000] [1] [ERROR] Worker (pid:7) exited with code 4 dwl_backend_rachid-web-1 | [2023-09-11 12:10:55 +0000] [1] [ERROR] Shutting down: Master dwl_backend_rachid-web-1 | [2023-09-11 12:10:55 +0000] [1] [ERROR] Reason: App failed to load. My docker-compose file looks like: version: "3.9" services: web: image: crdierenwelzijn.azurecr.io/web1 build: context: ./ dockerfile: Dockerfile.prod restart: always command: gunicorn DierenWelzijn.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/usr/src/app/staticfiles - media_volume:/usr/src/app/media expose: - 8000 env_file: - ./.env.prod proxy: image: crdierenwelzijn.azurecr.io/proxy1 build: context: ./proxy restart: always depends_on: - web ports: - 80:80 volumes: - static_volume:/home/app/staticfiles - media_volume:/home/app/media volumes: static_volume: media_volume: and the nginx.conf file looks like: upstream DierenWelzijn { server web:8000; } server { listen 80; server_name https://dockerdierenwelzijn.azurewebsites.net; location / { proxy_pass http://DierenWelzijn; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; client_max_body_size 10M; proxy_redirect off; } location /static/ { alias /home/app/staticfiles/; } location /media/ { alias /home/app/media/; … -
runtimeerror: cannot re-initialize cuda in forked subprocess
I have written a Django application which basically load a large language model (llama2-13b-chat-hf) with transformers (along with accelerator and bitsandbytes). I have a AWS P3.8xlarge instance and my code is loading the model with device_map=‘auto’ and with load_in_4bit=True. The purpose of this api is to generate the text for a given prompt as request. But when I am trying to host this application using gunicorn with the following command - gunicorn model_api.asgi:application -w 8 -k uvicorn.workers.UvicornWorker -b 0.0.0.0:8081 --preload it is getting loaded. But at the time of inference it is throwing the following error - runtimeerror: cannot re-initialize cuda in forked subprocess. to use cuda with multiprocessing, you must use the 'spawn' start method If I do not use --preload the model is getting loaded multiple times in the GPU memory. I need help to resolve the issue. -
Django add parameter to url after login fails, in custom authenticator
I override the authenticate function to return to login but with url parameters if the auth fails, simply for deferent javascript behavior's accounts/auth_backend/RoleModelBackend(ModelBackend)/authenticate() # if user pass or email or role is wrong login... else: login_url = reverse("login") redirect_url = login_url + "?" + urlencode({"user_type": role}) # role return redirect(request, redirect_url) mainAppName/urls urlpatterns = [ path("admin/", admin.site.urls), path("accounts/", include("accounts.urls")), ... ] accounts/urls urlpatterns = [ path("login", views.custom_login, name="login"), # Use the custom login view path("", include("django.contrib.auth.urls")), path("accounts/", include("django.contrib.auth.urls")), ] i get error Reverse for '<WSGIRequest: POST '/accounts/login/'>' not found. '<WSGIRequest: POST '/accounts/login/'>' is not a valid view function or pattern name. on the redirect line in authenticate() is there a better way to pass the frontend information other than url params? else how do i ge this to work? django 4.2 -
Mayan EDMS - not showing the uploaded docs
I'm working on a project to use one of the open source document system and work customize it based on the need, so I'm start installing Mayan EDMS with the following steps: Clone the repository https://gitlab.com/mayan-edms/mayan-edms Create a virtual environment python3 -m venv venv Activate the environment source venv/bin/activate Install the requirements pip install -r requirements.txt Run ./manage.py common_initial_setup Run python manage.py makemigrations Run python manage.py migrate Run the server python manage.py runserver All these steps done without errors but when access the Mayan on my local host and try to upload a document, this message appears but I cannot see the doc anywhere! The message appears after uploading Known that I can see the docs in the mayan/media/shared_files but the SQLite is empty and while uploading there is no any error! I search a lot to figure out the issue but I cannot find any solution I appreciate your support in this issue -
How to manage sessions in Django
Hi Ive created a django app that uses the spotify api to give users their top track and artist information, however, ive realised that my site if someone inputs the url /top-tracks without authenticating using the spotify auth they see the last users top track data. I was wondering how i go about this so that they have to authenticate themselves. Im new to app development any help would be appreciated. Repo: https://github.com/KevinL0206/spotify_stats_project from django.conf import settings from django.shortcuts import render, redirect from spotipy.oauth2 import SpotifyOAuth from django.http import HttpResponse from spotify_stats_project import settings from decouple import config from spotify_stats_project import settings from urllib.parse import urlencode from django.shortcuts import redirect from django.urls import reverse from django.http import HttpResponse import random import string import requests import base64 import datetime class SpotifyAPI(object): access_token = None access_token_expires = datetime.datetime.now() access_token_did_expire = True client_id = None client_secret = None scope = None redirect_uri=None token_url = "https://accounts.spotify.com/api/token" def __init__(self, client_id, client_secret,redirect_uri,scope, *args, **kwargs): super().__init__(*args, **kwargs) self.client_id = client_id self.client_secret = client_secret self.redirect_uri = redirect_uri self.scope = scope def is_token_expired(self): # Check if the access token has expired access_token = self.get_access_token() if not access_token: return True def login(self): authorization_url = 'https://accounts.spotify.com/authorize?' + urlencode({ "response_type" : "code", … -
Celery signatures .s(): early or late binding?
This blog post of Adam Johnson perfectly illustrates the difference between early binding and late binding closures in Python. This is also explained here. I've got a function my_func which corresponds to a Celery task (it's decorated with @shared_task). It expects some arguments. I run it with the following piece of code, using Celery signatures as described in the documentation (see also this StackOverflow answer): from functools import partial from django.db import transaction from example.tasks import my_func # next line can be found at the end of some other functions which involve a transaction transaction.on_commit(my_func.s(param1, param2).delay)) Are Celery signatures early binding or late binding? And how to demonstrate it in an elegant way? If they are early binding, the following line of code should be equivalent: transaction.on_commit(partial(my_func.delay, param1, param2)) If they are late binding, I think I could be facing a pesky bug with my current code, in some edge cases... -
Django url parameter setting
I try to have open url like: mysite.doamin/table/name1 mysite.doamin/table/name2 but without any success.... urls.py from django.urls import path from django.views.generic import TemplateView from . import views from .views import Table, TableFilter urlpatterns = [ path('', views.dashboard, name='dashboard'), path('table/<name>', Table.as_view(), name='table'), path('filters_form/', TableFilter.as_view(), name='filters_form'), path('search/', views.search, name='search'), ] template/navbar.html Table </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <li> <a class="dropdown-item" href="{% url 'table' cms %}">Cms</a> </li> <li> <a class="dropdown-item" href="{% url 'table' cms %}">Sectools</a> </li> </ul> I want to set a parameter, to switch de models and show any models in the table template.... Reverse for 'table' with arguments '('',)' not found. 1 pattern(s) tried: ['table\\/(?P<name>[^/]+)\\Z'] -
Working with DHL API in my Django project
I am trying to integrate DHL API in my django project but it is not working. Can someone help refer any comprehensive article on how to do it. I created an App on the DHL developer portal. I have my API Key and Secret Key -
validator could not be imported Check your AUTH_PASSWORD_VALIDATORS setting
i made validators.py and added my custom password validators like check for uppercase and special characters and after that i added those in my auth password validators in my settings.py like this AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 'OPTIONS': { 'max_similarity': 0.7, 'user_attributes': ("username", "first_name", "last_name", "email") } }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': { 'min_length': 8, } }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, \# custom coded validators { 'NAME': 'app1.validators.UppercaseValidator', }, { 'NAME': 'app1.validators.SpecialCharValidator', }, ] this is my forms.py ` from django import forms from django.contrib.auth.password_validation import validate_password class SignupForm(forms.Form): firstname = forms.CharField(max_length=20) lastname = forms.CharField(max_length=20) email = forms.EmailField() username = forms.CharField(max_length=30) password = forms.CharField(widget=forms.PasswordInput, validators=[validate_password])` and while signing up im getting this error ImproperlyConfigured at /signup/ The module in NAME could not be imported: app1.validators.UppercaseValidator. Check your AUTH_PASSWORD_VALIDATORS setting. Any help is appreciated before it is giving me error based on validators that django has bydefault but after adding my own validator it giving me error i mentioned -
Deploy Django to Vercel
error: 404: NOT_FOUND github: https://github.com/opielapatryk/python-portfolio Hello I have little problem with deploying my django portfolio. I was trying to deploy Django portfolio website to Vercel, but I have error mentioned above I was trying to edit path in vercel.json but nothing works -
Django-import-exportImport a ManyToMany field
I have a Agent class model class Agent(models.Model): registration_number = models.CharField(max_length=50, unique=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) And I have a AgentList class model class AgentList(models.Model): name = models.CharField(max_length=50) agents = models.ManyToManyField(Agent) What I want is when I click the "Import" button in my admin get a page with two field : Select the CSV (with the registration_number, first_name, last_name) Write a name for the list All agent will be saved in Agent and it will make a new "AgentList" link to those I imported. I already try some custom import page, but I'm starting to think it exist a better way. ATM my AgentListAdmin look like this : @admin.register(AgentList) class AgentListAdmin(ImportMixin, admin.ModelAdmin): list_display = ("name",) filter_horizontal = ("agents", ) def get_dataset(self, file): """ Returns the dataset from the uploaded file. """ dataset = tablib.Dataset() try: dataset.load(file.read().decode('utf-8'), format='csv') except Exception as e: raise ValidationError(str(e)) return dataset def import_action(self, request, *args, **kwargs): """ Import action. """ if request.method == 'POST': form = forms.Form(request.POST, request.FILES) if form.is_valid(): file = request.FILES['file'] dataset = self.get_dataset(file) result = self.process_dataset(dataset, request=request, confirm_form=None) if result.has_errors(): self.message_user(request, result, messages.ERROR) else: self.message_user(request, result, messages.SUCCESS) return HttpResponseRedirect(request.get_full_path()) else: form = forms.Form() context = self.admin_site.each_context(request) context.update( { 'form': form, 'opts': … -
badly formed hexadecimal UUID string
I don't understand what the problem here. -
How to use sitemap gemerator extention in vs code
I use sitemap generator extention in vs code to generate a sitemap for my website code in vs code, I works find but no url path for the sitemap was generated, pls how can I generate the url I tried vs code sitemap generator extention to generate a sitemap , sitemap.xml was generated without sitemap url -
Django - ValueError at / The 'image' attribute has no file associated with it
I am working on Django project I receive the following error: "ValueError at / The 'image' attribute has no file associated with it." models.py from django.contrib.auth.models import User from django.db import models # Create your models here. class Catagory(models.Model): name = models.CharField(max_length=255) class Meta: ordering = ('name',) verbose_name_plural = 'Catagories' def __str__(self): return self.name class Item(models.Model): Catagory = models.ForeignKey(Catagory, related_name='items', on_delete=models.CASCADE) name = models.CharField(max_length=255) description =models.TextField(blank=True, null=True) price = models.FloatField() image = models.ImageField(upload_to='item_images', blank=True, null=True) is_sold = models.BooleanField(default=False) created_by = models.ForeignKey(User, related_name='items', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name html <div class="card" style="width: 18rem;"> <img src="{{ item.image.url }}" class="card-img-top" alt="image"> <div class="card-body"> <h5>{{ item.name }}</h5> <p class="text-secondary">Price: {{ item.price }}</p> </div> </div> Error during template rendering How can I handle this error -
Shopify Django App Admin Link Not working After Deploying on Amazon EC2 Instance
I have made a test Shopify app in Django. What this app essentially does is downloads invoice of orders through Shopify admin dashboard admin links. The app was working fine on my local host when I was using ngrok tunnels. The invoices were being downloading on command but when I deployed this app on an AWS EC2 Instance the admin links are not working. The Invoice Pdf is being generated properly but I guess it is not being sent as an HttpResponse. def download_invoice(request, raw_order, template_name): raw_order['product_data'] = product_data dir_path = settings.MEDIA_ROOT with tempfile.TemporaryDirectory(dir=dir_path) as tmpdir: output_filename = tmpdir + '\\' + "my-invoice.pdf" path=os.path.join(os.path.dirname(__file__),'./templates/home') templateLoader = jinja2.FileSystemLoader(searchpath=path) templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = template_name template = templateEnv.get_template(TEMPLATE_FILE) outputText = template.render(data=raw_order) pdfkit.from_string(outputText, output_filename) filename = "my-invoice.pdf" wrapper = FileWrapper(open(output_filename, 'rb')) print(output_filename) # breakpoint() # pass response = HttpResponse(wrapper, content_type=mimetypes.guess_type(output_filename)[0]) response['Content-Length'] = os.path.getsize(output_filename) response['Content-Disposition'] = "attachment; filename=" + filename return response This function downloads the pdf when it is called on my app's interface but it does not download the invoice when it is called in Shopify Admin Link. Maybe there is an issue EC2 security group. My Inbound Rules My Outbound Rules As far as I think there is some problem with … -
Web Frontend Development: What way should I choose? [closed]
I have a Django project in which I want to show a different page depending on the screen size the user has. If they are on a mobile device, I want them only to see a column of buttons with all the urls references on the whole screen ( Like a pile of buttons one on top of the other). When they are on a computer screen, I already have a predefiened template. Whats the best approach for this matter ? I searched for Django options and try with https://pypi.org/project/django-mobile-detect/ but I didnt manage to get it that way. Im new in front end and I dont want to mess my current progress. What method should I use ? pip install django-mobile-detect I try with this django mobile detect repo and try with mobil.detectMiddleware.