Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Allow Users to Specify SESSION_COOKIE_AGE in Django at Runtime
I'm specifying a default SESSION_COOKIE_AGE in the main settings.py file; however, I'd like admin users to be able to overwrite this value. This value should persist across server restarts. My initial reaction was to store this in a single-row in a DB table and then write some middleware that would adjust the user's expiry date on each request to match the user-supplied SESSION_COOKIE_AGE; however, that seems like a lot of redundant db queries. Then I went down a signals rabbit hole and am considering creating two signals (post_save and connection_created) to handle: user updates to the user-supplied SESSION_COOKIE_AGE value stored in the DB as well as ensuring SESSION_COOKIE_AGE is updated upon the server starting. And finally I see all of these projects like django-constance, etc. to dynamically update settings constants at runtime. Any suggestions on the most reliable / least error-prone architecture for this? -
Django not keeping session entries after allauth social login/signup
I have an authorized user that is adding a social account to his account. I want the user to be redirected to the specific url after they signed up for this account. next parameter is not working so I decided to go with session way. I've overridden DefaultAccountProfider which checks session for next key. The problem is that there is no such key after signup/login. Please, note that this applies on already logged in User. class MyAccountAdapter(DefaultAccountAdapter): def get_signup_redirect_url(self, request): request.session['next'] # keyerror return super().get_signup_redirect_url(request) # breakpoint here def get_login_redirect_url(self, request): request.session['next'] # keyerror return super().get_login_redirect_url(re..) # breakpoint here - no "next" session How can I make it work? I need the user to be redirected to /some-url but only when next is in the session. -
AttributeError at /cart type object 'Cart' has no attribute 'model'
class Cart(View): def get(self , request): customer_id = request.session['customer'] cart = get_object_or_404(Cart, customer_id= customer_id) return render(request , 'cart.html') I am not able to get the cart object -
NGINX Static Files Over Https?
I have the following docker-compose set up that is working for displaying pictures when deployed locally and without https: NGINX: events{ } http{ server { listen 80; server_name localhost; root /usr/share/nginx/html; location / { proxy_pass http://frontend:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection ""; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } } } docker-compose: frontend: build: context: ../../ restart: always volumes: - '../../:/app' - '/app/node_modules' ports: - "3000:3000" depends_on: - "backend" environment: - CHOKIDAR_USEPOLLING=true stdin_open: true tty: true nginx: build: context: ../../nginx restart: always ports: - "80:80" - "443:443" volumes: - volume1:/usr/share/nginx/html links: - "backend" - "db" - "frontend" frontend: <img onError={()=>{ console.log("inside the onError function") setImgError(true) }} src={"http://localhost:9000/static/"+comment.file_name} className='commentimage' /> This is not working when using https. Which is to say - / and /api/ work as expected but not /images/. events{ } http{ server { listen 80; server_name localhost lightchan.org www.lightchan.org; root /usr/share/nginx/html; location /.well-known/acme-challenge/ { root /var/www/certbot; } return 301 https://lightchan.org$request_uri; } server { listen 443 default_server ssl http2; listen [::]:443 ssl http2; server_name localhost lightchan.org www.lightchan.org; #ssl_certificate /etc/nginx/ssl/live/lightchan.org/fullchain.pem; #ssl_certificate_key /etc/nginx/ssl/live/lightchan.org/privkey.pem; ssl_certificate /etc/letsencrypt/live/lightchan.org/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/lightchan.org/privkey.pem; location / { proxy_pass http://frontend:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } location ^~ /api/ { … -
How to put data in the db when you press a link in django
<a href="{% url 'one' one.id_n %}" class="bg-gray-900 shadow-lg rounded p-3 overflow-hidden hover:shadow-xl hover:scale-105 duration-500 transform transition cursor-pointer"> <div class="group relative"> <img class="w-full md:w-72 block rounded" src="{{ one.f1 }}" alt="" /> </div> </a> I'm begginer with django and i want to add data as "one.id_n" to the db when you press the link. -
How to hide/delete recent actions dashboard from django admin panel?
I have removed my model but the history stays the same in the recent actions dashboard. I want to either clean it or delete it. Someone please say that way. -
Django REST Framework ValidationError along with params
The ValidationError raised by Django REST Framework doesn't include params like how Django's Validation error includes it. The REST Framework catches Django's Validation Error and raises it's Validation error which doesn't include params. Is there any way to keep params in the REST Framework ValidationError which are raised by Django's Validation Error? -
How to Hide a "fieldset" if user role changes in admin
Hi I want to hide some fieldsets in admin if user role changes. In get_queryset() I'm changing queryset if role == 'CMS' I also want hide Permission fieldset for same role. Here is my admin: from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import Permission from .models import BankAccount from addresses.models import Address User = get_user_model() class AddressInline(admin.TabularInline): model = Address extra = 0 @admin.register(User) class UserAdmin(BaseUserAdmin): list_display = ( 'id', 'full_name', 'email', 'gender', 'role', ) list_filter = ( 'gender', 'is_staff', 'is_superuser', 'is_active', ) list_display_links = ( 'full_name', 'email', ) search_fields = ( 'email', 'first_name', 'last_name', 'phone_number', ) readonly_fields = ( 'created', 'updated', ) ordering = ('first_name', 'email', 'last_name',) fieldsets = ( ('Credentials', {'fields': ('email', 'phone_number', 'password')}), ('Info', {'fields': ('first_name', 'last_name', 'gender', 'role', 'otp', 'profile_pic', 'created', 'updated')}), ('Permissions', {'fields': ('is_vendor', 'is_staff', 'is_superuser', 'is_active', 'groups', 'user_permissions')}), ) add_fieldsets = ( ('Credentials', {'fields': ('email', 'phone_number', 'password1', 'password2')}), ('Info', {'fields': ('first_name', 'last_name', 'gender', 'role', 'profile_pic')}), ('Permissions', {'fields': ('is_vendor', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), ) inlines = (AddressInline,) def full_name(self, obj=None): return f'{obj.first_name} {obj.last_name}' def get_queryset(self, request): if request.user.role == 'CMS': return self.model.objects.filter( role='CUSTOMER', is_staff=False, is_superuser=False ) else: return self.model.objects.all() admin.site.register(Permission) admin.site.register(BankAccount) In this admin, in get_queryset() … -
Organize folder by date using django filer
I'm using django-filer to be able to reuse the already uploaded images. Everything works fine, except the folder path. I want all FilerImageFields to store images in a structured folder like this (year/month/filename.jpg) : Is there a way to do it? Thanks. -
AttributeError at /cart 'dict' object has no attribute 'append'
class Cart(View): def get(self , request): categories = Category.get_all_categories() productid = request.GET.get('product') product = get_object_or_404(Products, id=productid) sellername = request.GET.get('seller') seller = get_object_or_404(Sellers, name=sellername) productsToShow = [] if('cart' in request.session): productsToShow = request.session['cart'] prices = Price.objects.filter(product=product,seller=seller) for price in prices: product2 = price.product product2.seller = price.seller product2.cost = price.cost product2.quantity = 1 productsToShow.append(product2) request.session['cart'] = productsToShow return render(request , 'cart.html' , {'products' : productsToShow,'categories' : categories} ) session variable wont let me get and set -
How to add URL parameters to Wagtail archive page with filter form?
This is about an archive page in Wagtail CMS where a large number of posts can be filtered by certain properties. The filtering is handled by a form with a few select elements. The form is validated in the serve() method of the page. The queryset is filtered there accordingly as well. Here is some exemplary code to illustrate what I mean: from .forms import ArchivePageFilterForm ... class ArchivePage(Page): ... def pages(self): return SomeModel.objects.live() # exemplary queryset def serve(self, request): filter_form = ArchivePageFilterForm(request.POST or None) if request.method == 'POST': if filter_form.is_valid(): name = filter_form.cleaned_data['name'] category = filter_form.cleaned_data['category'] color = filter_form.cleaned_data['color'] whatever = filter_form.cleaned_data['whatever'] selected_pages = filter_query(self.pages, name, category, color, whatever) # imagine some filtering magic here return render(request, 'pages/archive_page.html', { 'page': self, 'pages': selected_pages, 'form': ArchivePageFilterForm(initial={'name': name, 'category': category, 'color': color, 'whatever': whatever}), }) return render(request, 'pages/archive_page.html', { 'page': self, 'pages': self.pages, 'form': ArchivePageFilterForm(), }) The RoutablePageMixin did not work for me here, because it only works with fixed URL schemes. I wonder how I can add URL parameters only as needed, one by one, depending on the active filters. Exemplary URLs that would be possible with the same page: .../archive/?name=janedoe .../archive/?name=janedoe&type=essay .../archive/?category=essay .../archive/?category=essay&color=green&whatever=foobar ... you get the idea. The … -
How to loop through xlif(xml) to find specifc ids are exists
I have xliff file in below format which located in s3 <xliff xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="" version="2.0"> <file original="page_4" trgLang="en-GB"> <group id="chapter0"> <unit id="chapter00__title"> <segment> <source>chapter 01</source> </segment> </unit> <unit id="chapter0__introduction"> <segment> <source /> </segment> </unit> <unit id="chapter0__text"> <segment> <source>hello</source> </segment> </unit> <unit id="uexercise0__answers[0].correct"> <segment> <source>111</source> </segment> </unit> I access it via s3_object = s3.get_object(fileLink) read_file = s3_object['Body'].read() I want to loop through ids and validate if all required ids are available on xliff I have below loop with ids which required, for x in groups: for attribute, value in x.localized_strings: print(attribute) # ex: attribuete = chapter00__title I need to loop over my xliff file and see if all attrbutes are availabe, if it found any missing attribute or new attribute then throw error please advice how to proceed this -
plotly django bar doesn't show chart
if i print df_costo the result of the dataframe is ok, but in html file doesn0t show nothing ''' code ''' def fase_progetto(request): try: qs_costo = CostoFase.objects.all() costo_fase_data =[ { 'Responsabile': x.responsabile, 'Costo': x.costo } for x in qs_costo ] df_costo = pd.DataFrame(costo_fase_data) print(df_costo) fig_costo = px.bar(df_costo, x="Responsabile", y="Costo") gantt_plot_costo = plot(fig_costo, output_type="div") context = {'costo_plot_div': gantt_plot_costo, 'form': form} return render(request, 'progetti/progetti.html', context) except: return render(request, 'progetti/progetti.html', {'form': form}) -
invalid literal for int() with base 10: b'20 Feb'
I am working with Wagtail and I am creating the model of the app. publish_date = models.DateField( max_length=300, blank=True, null=True, default="20 Feb", verbose_name="First publish date", help_text="This shows the first publish date" ) I think the problem is that the field type is a DateField but the value that I am sending is '20 Feb'. Any ideas? -
Django Display ID and Description From Queryset Form into Dropdown
I would like to display data from the table into Django Queryset Form with properly showing value and text of dropdown control. Coding at Form: self.fields['testing_field'].queryset = model_abc.objects.all().values_list('description', flat=True) Result description is also value: <select name="cars" id="cars"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> </select> Result expection can set id as value with existing description: <select name="cars" id="cars"> <option value="1">Volvo</option> <option value="2">Saab</option> <option value="3">Mercedes</option> <option value="4">Audi</option> </select> How to set id as a value within the dropdown form of Django QuerySet ? -
How to invalidate a view cache using django-cacheops
I'm having a view and I cached it in views.py using django-cache(https://github.com/Suor/django-cacheops) @cached_view(timeout=60*15) @csrf_exempt def order(request, usr): ... and the regex for order view in urls.py url(r'^order/(?P<usr>\D+)$', views.order, name='ord') #Example Url: http://127.0.0.1:8000/order/demo (demo is the user name) And I want to invalidate the cached view order inside the below view @login_required def available(request, pk, avail): pk = int(pk) avail = strtobool(avail) if avail: Product.objects.filter(id = pk).update(available = True) else: Product.objects.filter(id = pk).update(available = False) return HttpResponseRedirect(reverse_lazy('yc')) According to docs we can achieve this by doing @login_required def available(request, pk, avail): pk = int(pk) avail = strtobool(avail) if avail: Product.objects.filter(id = pk).update(available = True) order.invalidate("http://127.0.0.1:8000/order/demo", "demo") #it's a dummy url I've handled it dynamically in my code else: Product.objects.filter(id = pk).update(available = False) order.invalidate("http://127.0.0.1:8000/order/demo", "demo") #it's a dummy url I've handled it dynamically in my code return HttpResponseRedirect(reverse_lazy('yc')) But it's not working. Here are my logs using redis-cli **1647434341.849096 [1 [::1]:59650] "GET" "c:af687d461ec8bb3c48f6392010e54778" 1647434341.866966 [1 [::1]:59650] "SETEX" "c:af687d461ec8bb3c48f6392010e54778" "900" "\x80\x04\x95\xfa\b\x00\x00\x00\x00\x00\x00\x8c\x14django.http.response\x94\x8c\x0cHttpResponse\x94\x93\x94)\x81\x94}\x94(\x8c\b_headers\x94}\x94\x8c\x0ccontent-type\x94\x8c\x0cContent-Type\x94\x8c\x18text/html; charset=utf-8\x94\x86\x94s\x8c\x11_closable_objects\x94]\x94\x8c\x0e_handler_class\x94N\x8c\acookies\x94\x8c\x0chttp.cookies\x94\x8c\x0cSimpleCookie\x94\x93\x94)\x81\x94\x8c\x06closed\x94\x89\x8c\x0e_reason_phrase\x94N\x8c\b_charset\x94N\x8c\n_container\x94]\x94B\xed\a\x00\x00<!DOCTYPE html>\n\n<html>\n <head>\n <meta charset=\"utf-8\">\n <title>Buy Products</title>\n <link href=\"https://fonts.googleapis.com/css?family=Peralta\" rel=\"stylesheet\">\n <link rel=\"stylesheet\" href=\"/static/css/bootstrap.min.css\">\n <link rel=\"stylesheet\" href=\"/static/css/app.css\">\n </head>\n <body>\n <div class=\"wrapper\">\n <div class=\"container\">\n <ol class=\"breadcrumb my-4\">\n <li class=\"breadcrumb-item active\" style=\"color: #000;\">Buy Products</li>\n </ol>\n <form method=\"post\">\n <!-- <input type=\"hidden\" name=\"csrfmiddlewaretoken\" value=\"SnsBnyPIwIDejqctR7TMNkITcSafgwiydwsyIiAKQkiSvr3nFA0cm1Tf3Mk6JTPj\"> -->\n <p><label … -
Gunicorn failed Triggered by gunicorn.socket: Failed with result 'exit-code'. error
I'm trying out a simple Django deployment app on VPS using this url. I went through every step of the work and successfully ran this project via python manage.py runserver where there isn't a mistake, but when I try to implement it with unicorn its launch following error ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Wed 2022-03-16 11:28:04 CET; 22h ago TriggeredBy: ● gunicorn.socket Main PID: 5578 (code=exited, status=2) Warning: journal has been rotated since the unit was started, output may be incomplete. Here are the files nano /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target nano /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=www-data WorkingDirectory=/home/pawnhost/page_builder ExecStart=/home/pawnhost/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind /run/gunicorn.sock \ pawnhost.wsgi:application [Install] WantedBy=multi-user.target systemctl status gunicorn.socket ● gunicorn.socket - gunicorn socket Loaded: loaded (/etc/systemd/system/gunicorn.socket; enabled; vendor preset: enabled) Active: active (listening) since Thu 2022-03-17 09:58:53 CET; 25min ago Triggers: ● gunicorn.service Listen: /run/gunicorn.sock (Stream) CGroup: /system.slice/gunicorn.socket Mar 17 09:58:53 mail2.pawnhost.com systemd[1]: Listening on gunicorn socket. systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Wed 2022-03-16 11:28:04 CET; 23h ago TriggeredBy: … -
PermissionError when uploading file on new production server
I migrated my Django project to a new production server. On the previous production server, everything worked fine. While migrating, I upgraded to Ubuntu 20.04 and Django 4.0.3. Now everything is working again, except for the uploading of files. When I try to create an instance of an Invoice object, it works, as long as I don't try to upload a file along with it. Adding an invoice with a file gives the following errors: Internal Server Error: /stock/create_invoice Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/www/html/stock/views.py", line 346, in create_invoice invoice.save() File "/usr/local/lib/python3.8/dist-packages/django/db/models/base.py", line 806, in save self.save_base( File "/usr/local/lib/python3.8/dist-packages/django/db/models/base.py", line 857, in save_base updated = self._save_table( File "/usr/local/lib/python3.8/dist-packages/django/db/models/base.py", line 1000, in _save_table results = self._do_insert( File "/usr/local/lib/python3.8/dist-packages/django/db/models/base.py", line 1041, in _do_insert return manager._insert( File "/usr/local/lib/python3.8/dist-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.8/dist-packages/django/db/models/query.py", line 1434, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/usr/local/lib/python3.8/dist-packages/django/db/models/sql/compiler.py", line 1620, in execute_sql for sql, params in self.as_sql(): File "/usr/local/lib/python3.8/dist-packages/django/db/models/sql/compiler.py", line 1547, in as_sql value_rows = [ File "/usr/local/lib/python3.8/dist-packages/django/db/models/sql/compiler.py", line 1548, in <listcomp> [ File "/usr/local/lib/python3.8/dist-packages/django/db/models/sql/compiler.py", line 1549, in <listcomp> self.prepare_value(field, self.pre_save_val(field, obj)) File "/usr/local/lib/python3.8/dist-packages/django/db/models/sql/compiler.py", … -
failed to get real commands on module "": python process died with code 1
I have a Django project in which I created several custom Django management commands. For some reason I can't explain, I got this error: "failed to get real commands on module "": python process died with code 1: command '' took too long and may freeze everything. consider adding it to 'skip commands' list" Although there are many questions on Stackoverflow on this topic I can't find the reason of why I am getting this error. It doesn't seem to me that this is a Pycharm bug (like in 2015). Could someone explain this error to me? What is it due to? -
Current datetime according to the timezone of the object in a query
I have a model that represents a restaurant: class Restaurant(models.Model): timezone = models.CharField(_("Timezone"), max_length=128, null=True, blank=True) ... I need to process restaurants if the current time for that restaurant is greater than 8:00h (start working day). How could I create an annotation with the current datetime for each restaurant to use in a query? I would like something like this: Restaurant.objects.annotate(restaurant_datetime=timezone.now().astimezone(pytz.timezone(timezone_of_the_restaurant))) -
channels slows app and creates many HTTP 500 errors
I use channels to inform the frontend of my app to force a page update. What I discovered is, that it is much slower in debug mode now and also I have tons of HTTP 500 in my webconsole. Occasionally I end up with: ERROR:daphne.server:Exception inside application: Single thread executor already being used, would deadlock Traceback (most recent call last): File "...\venv\lib\site-packages\channels\staticfiles.py", line 40, in __call__ return await self.staticfiles_handler_class()( File "...\venv\lib\site-packages\channels\staticfiles.py", line 56, in __call__ return await super().__call__(scope, receive, send) File "...\venv\lib\site-packages\channels\http.py", line 198, in __call__ await self.handle(scope, async_to_sync(send), body_stream) File "...\venv\lib\site-packages\asgiref\sync.py", line 382, in __call__ raise RuntimeError( RuntimeError: Single thread executor already being used, would deadlock And also all the HTTP 500 errors are usually some resources that can not be loaded - icons and other static files. Loading the page can last forever, but I remember for some time it worked just fine. I am using django-eventstream for creating my channels. How would I find out what is slowing me down, or how can I prevent it? Is my problem (probably) similar to this one: Django and Channels and ASGI Thread Problem? -
Filter query through an ID to another table in Django
Let's say I have this query Table 1 cardId = 1 table_1 = card_tbl.ocabjects.get(id=cardId).values('category1_id') and the Output for this is Table 1 is <QuerySet [{'category1_id': 1}]> Next is I want to match the value of table 1 to table 2 Table 2 table_2 = category1_tbl.objects.filter(Q(id=table_1)) The table 2 contains column which is a name and I want just to get result name through matching ID from different table for example jason Need help -
If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import
I get an circular import or " does not appear to have any patterns in it" error although I am sure of my spelling and syntax. searched in the internet but most of the problems I found were spelling or syntax related. This is my code: urls.py : from django.urls import path from hi import views urlpattern=[ path("", views.howarey, name="x") ] views.py: from django.http import HttpResponse from django.shortcuts import render # Create your views here. def howarey(request): return HttpResponse("hi") settings.py : INSTALLED_APPS = [ 'hi', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] urls.py: from xml.etree.ElementInclude import include from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('hi/', include("hi.urls")) ] The error from The CMD: raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'hi.urls' from 'C:\\Users\\ahmad\\mx\\hi\\urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import. -
Django not show checkbox in html
I want to set checked in checkbox. This is html code if device.status is True then set checked in checkbox. {% for device in device %} <h2>status = {{device.status}}</h2> <!-- Rounded switch --> <label class="switch"> <form action="addStatus" method="post"> {% csrf_token %} {% if device.status == 1 %} <input type="checkbox" name="status" onChange="this.form.submit()" checked> {% else %} <input type="checkbox" name="status" onChange="this.form.submit()" > {% endif %} </form> </label> {% endfor %} It can show status = True but not show checkbox. How to fix it? -
Django give permissions to users per company
In my case I have different users which can be part of different companies. An user can belong to multiple companies and a company has multiple customers, products, services, … Now I want the user to be able to have different permissions per company. So let’s say user X can manage the customers in company A but can only read the products and services. And user X can manage the users, products and services in company B. I would like to work with roles: so manage everything would be the role “superadmin” and manage customers but read products and services would be the role “sales” for example. So in short: I want to create roles where I can assing permssions to and then add these roles to users per company. I am planning on using rsinger86/drf-access-policy to manage access control but any suggestions are welcome. Please suggest me a good way to accomplish this scenario. How am I able to add roles per company and am I still able to use the by-default-generated auth_permissions from Django? Thank you in advance!