Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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! -
{ "product": [ "This field is required."] } in Django REST API
This is my models and I defined set null=True, blank=True for foreign key relations but when I hit my API then API response raised that { "product": [ "This field is required."] }. What I wrote wrong. please help me. **Here is my model:** class CashSell(models.Model): user_profile = models.ForeignKey('accounts.UserProfile', on_delete=models.CASCADE) product = models.ForeignKey('inventory.Product', on_delete=models.CASCADE, related_name='cash_sell', null=True, blank=True) cash_sell_debit = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) description = models.CharField(max_length=250) date = models.DateField() picture = models.ImageField(upload_to='cash_sell_pics', blank=True, null=True, default='images.png') def __str__(self): return self.user_profile.first_name class Meta: verbose_name = "Cash Sell" verbose_name_plural = "Cash Sell" -
How to design django app with integrated gRPC server?
I am currently working on a django project where I need a separate backend application to be able to initiate gRPC requests to my django frontend. Simply put: I want the backend to be able to access and change objects. Therefore I need my django project to also start my grpc server while starting up. I did a lot of research and didn't really find any best practice on that. As far as I would imagine, I could override the startup command of django to also start my grpc server on a seperate thread. But I am afraid that I will end up with a very bad practice solution. Is there any recommendable way to do this? I am excited about every hint :) -
How to query all the fields in parent as well as child model related with a foreign key in Django ? where id matches to the parent class?
I have 3 models in this project class products(models.Model): product_id = models.CharField(max_length=10, blank=False, null=False, primary_key=True) name = models.CharField(max_length=20, blank=False) description = models.TextField(blank=True, null=True) userslikedproduct = models.ManyToManyField(UserAccount, blank=True) def __str__(self): return self.product_id class productReviews(models.Model): review_id = models.CharField(max_length=10, blank=False, null=False, primary_key=True) product = models.ForeignKey(products, related_name='reviews', on_delete=models.CASCADE) user = models.ForeignKey(UserAccount, related_name='users', on_delete=models.CASCADE) review_desc = models.TextField(blank=True, null=True) review_rating = models.IntegerField(choices=RATING, null=True) date_added = models.DateTimeField(verbose_name='date_added', auto_now_add=True) class ReviewImage(models.Model): review = models.ForeignKey(productReviews, related_name='review_images', on_delete=models.CASCADE) image = models.ImageField(null=True, blank=True, upload_to="/images/") I want to fetch all the reviews related to a product id along with review images. I tried using Query1 = productReviews.objects.all().filter(product=product).values().order_by('-date_added') Query2 = ReviewImage.objects.filter(review__product__product_id=product).values_list('review', 'image') Query1 results in all the objects without images Query2 reults in all the images and review ids without review objects How can I fetch all the reviews of one particular product along with the review images? -
Getting url of image on django/wagtail site
I have a wagtail site - where blogpages are rendered by looping through a streamfield (in which each block can have an image, a heading and some text): <div class="col-md-8 mx-auto px-auto"> <div class="conundrum mb-3">{{ page.category }}</div> <h1>{{ page.title }}</h1> <p class="meta">{{ page.date }}</p> <div class="intro my-4 py-4">{{ page.intro }}</div> {% for block in page.content %} <div class="pb-4"> {% image block.value.image fill-1000x500 class='blog_image' %} <h2 class="py-2 my-2"> {% include_block block.value.heading %} </h2> {% include_block block.value.text %} </div> {% endfor %} </div> I want the 'tweet this' button on the blogpage to include the first image on that page. <meta name="twitter:card" content="summary" /> <meta name="twitter:site" content="@PsymatikDotCom" /> <meta name="twitter:title" content="{{page.title}}" /> <meta name="twitter:description" content="{{page.intro}}"/> <meta name="twitter:image" content="https://how_do_i_get_this_path" /> But it is not clear to me how to dynamically grab the url of the first image to enter it in the twitter:image section? -
I have followed the azure app service documentation but wasn't able to deploy my app and failed drastically. please if anyone can help me out
I have followed the azure app service documentation but wasn't able to deploy my app and failed drastically.. please if anyone can help me out with this https://github.com/akj1608/bicaption/runs/5498451909?check_suite_focus=true https://github.com/akj1608/bicaption https://frts.azurewebsites.net/ if anyone can help, please do!