Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show __str__ representations for existing Inline objects in the admin UI, but still use the form for adding new objects
I have a Django Admin view with a number of inlines. The 'Add another ' works as expected and brings up an empty form to fill in the values. Once added though, it shows that related object in form view, and all fields on all inlines remain editable. What I'd like to achieve is that all existing objects are listed in their __str__ representation, but the 'Add another' button still brings up the form. Can this be done in Django Admin, or am I looking for too much? -
Keep on getting this error message when trying to run my django server: [Errno 2] No such file or directory
I'm trying to run my django server but keep on getting this error, [Errno 2] No such file or directory. I tried using the cd manage.py command but also got this error cd : Cannot find path 'C:\Users\nyaknoiton\Desktop\Django 2\manage.py' because it does not exist. -
Django model for ordered list with polymorphic relations
I am trying to figure out the way to implement a Django model for optical/mechanical simulations for photovoltaic modules and glazing units. The simplest real-life representation of the problem looks like this: Position Material 1 Glass 2 EVA foil 3 Solar cells 4 EVA foil 5 PVF Here is my idea of the data representation: The class PVmodule class handles has the ForeignKey field referencing its composition like so: class PVmodule(models.Model): #---components---# composition = models.ForeignKey(ModuleComposition,related_name="composition",on_delete=models.CASCADE) The class ModuleComposition is an abstraction of an optical stack (as in the table above) - set of ordered materials like glass, gas, coatings and polymers... each represented by separate django model. Upon save() it handles optical calculations based on the ManyToMany relation with the StackItem class and fills in its' remaining fields with data automatically: class ModuleComposition(models.Model): self.stack = models.ManyToManyField(StackItem) The StackItem class is a representation of a single material on a specific position. It relates via ForeignKey to a table handling the specific material parameters. class StackItem(models.Model): self.position = models.PositiveIntegerField() self.material = models.ForeignKey( ... ) I would like this allows the user to define the module composition step by step or to an already existing module composition for quick evaluation. However, I cannot … -
Automatically update and render item quantity on cart update
I have been working on my cart functionality but I cannot seem to get the cart item.quantity to automatically update without a page refresh. I'm wondering how I could modify the code below to not only update my CartIcon but update specific item quantity too or whether I need a new function/util entirely. Here is the HTML snippet with the variable {{item.quantity}} I would like to automatically update when the quantity is changed. <svg class="icon--cart change-quantity update-cart" data-product="{{item.product.id}}" data-action="add" > <use href="/media/sprite.svg#plus-solid"/> </svg> {{item.quantity}} <svg class="icon--cart change-quantity update-cart" data-product="{{item.product.id}}" data-action="remove"> <use href="/media/sprite.svg#minus-solid"/> </svg> Here is a util I made for updating the Cart Icon number in my header: @login_required def get_cart_quantity(request): cart = get_object_or_404(Cart, user=request.user) quantity = sum(item.quantity for item in cart.items.all()) return JsonResponse({'quantity': quantity}) Here is my current script that successfully updates my CartIcon: function updateCartQuantity() { fetch("/get_cart_quantity/") .then((response) => response.json()) .then((data) => { document.getElementById("cart-quantity").textContent = data.quantity; }) .catch((error) => { console.error("Error fetching cart quantity:", error); }); } // Call updateCartQuantity when the page loads and after adding an item to the cart window.addEventListener("load", updateCartQuantity); Below is the quantity field I want to automatically update, so it is specific to the item, not the whole cart quantity. -
Limit the number of objects in django TabularInline
I use Django, and I want create a TabularInline showing a maximum of 10 results You can configure it with max_num and extra, but that does not limit the results. They have a special section on "Limiting the number of editable objects". Where they say "max_num does not prevent existing objects from being displayed". But also not how its actually done. I can also not overwrite the get_queryset method because Django does a filter later and then I get TypeError: Cannot filter a query once a slice has been taken. Does anyone know how I can do this? -
Create Cart object once user logs in
My app is built so that only authenticated users can purchase items so there is only need for a cart when the use logs in, my script then pulls the cart id that relates to that user so my API can work its magic. I cannot get the Cart object to be created. I have tried many attempts and this is my latest: ef user_login(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) try: cart = Cart.objects.get(user=user) except Cart.DoesNotExist: cart = Cart.objects.create(user=user) request.session['cart_id'] = cart.id messages.success(request, ("You were successfully logged in...")) else: messages.success(request, ("There was an error logging in, please try again...")) return redirect('home') return render(request, 'authenticate/login.html', {}) -
Selecting a database to use per specific APIView in the Django application
Recently I added a second database to my Django application. I have prepared API a long time ago with the use of djangorestframework and now I would like to be able to choose which view should use which database. I tried using Database Router however, I do not think it suits my need cause many of my views use the same models. I also hope to find a more elegant solution than just adding .using() method to every single query. -
DatabaseError at /admin/core/profile/add/ No exception message supplied
I am building class models using Django and mongodb is connected to my server successfully. When I create User account as UserAdmin, I can create and save new data and everything is snyc to my database. However, when UserAdmin or superuser tried to create a Profile, which is built by using foreign key User model, I got this error. I tried to fix this error by downgrading django and djongo, but local testing worked well but server got crashed. So downgrade the package is not a solution. How can I this database error?... I've been trying to fix this for 3 days, but i still got lost and do not know which part is wrong like either my code or my db setting .... here is my model.py and admin.py code. Please lmk if u want more information.. from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, username, email, password=None, role=None): if not username: raise ValueError('Users must have a username') if not email: raise ValueError('Users must have an email address') user = self.model( username=username, email=self.normalize_email(email), role=role ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password, role=None): user = self.create_user( username=username, email=email, password=password, role=role ) … -
Django Count in Annotate and Subquery are much slower than simply iterating over my items and filtering individualy
I'm trying to count how many documents per project (among other things) have been registered, Registered also holds other values like DateTime and User (just a disclosure they are unrelated to my issue). Iterating through a list and querying ~54 times ends up being much faster than Annotate or Subquery (13 vs 27 seconds) I have 4 tables which go like this Project -> Batch -> Document -> Registered. Right now we have 54 Projects, 20478 Batches, 3231095 Documents and 312498 Registered. The timings listed below are for the entire view, not just the bits represented, but you can have an idea on their impact... projects = Project.objects.filter(completion_date__isnull=True) # "Fast", takes around 13.5 seconds to evaluate for project in list(projects.values('id')): count = Document.objects.filter(batch__project_id=project['id], registered__isnull=False) # Both methods below are much slower, taking around 27 seconds to evaluate # Simple annotation projects = projects.annotate(count=Count('batches__documents', filter=Q(batches__documents__registered__isnull=False), distinct=True)) # An attempt to simulate the first list iteration query without multiple db hits, ends up exactly as slow as annotate subq_registered = Document.objects.filter(batch__project_id=OuterRef('id'), registered__isnull=False).annotate(count=Func(F('id'), function='Count')).values('count') projects = projects.annotate(count=Subquery(subq_registered)) I expected Subquery to be faster than my first method, as it would mimic it, but its just as slow as simple count + annotation. Is … -
Django Views "PageNot Found"
i have a password change page and i want to move it to another page after successfully changing my password, but my code is giving me a page "page not found" path( "passwordchange/", auth_views.PasswordChangeView.as_view( template_name="user/passwordchange.html", form_class=PasswordChangeForm, success_url="/passwordchangedone/" ), name="passwordchange", ), path( "passwordchangedone/", auth_views.PasswordChangeDoneView.as_view(template_name="user/passwordchangedone.html"), name="passwordchangedone", -
set models of a school in django
i want to create a school like tables in django: where a teacher has few classroom and a classroom has only one teacher and a student who has one classroom but a classroom has many students i build my models like this: class Classroom(models.Model): classID = models.CharField(primary_key=True,validators=[MinLengthValidator(2)], max_length=50, blank=False) class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) school_name = models.CharField(validators=[MinLengthValidator(2)], max_length=50, blank=False) city = models.CharField(validators=[MinLengthValidator(2)], max_length=50, blank=False) classroom = models.ForeignKey(Classroom) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) fullName = models.CharField(validators=[MinLengthValidator(2)], max_length=50, blank=False) studentLevel = models.IntegerField(default=0) studentUnit = models.IntegerField(default=0) classroom = models.ForeignKey(Classroom) done = models.BooleanField(default=False) is it ok to do it like this because i get confused with the relations -
How to store temporary data in Django?
I'm creating an app on Django: it's a collaborative game with a chat. Every time you join a game, you choose a nickname, and it exists until you leave the game. Also chat: it is stored until the end of the game. What is the best way to store nicknames and chat? i'm a beginner and don't understand that really... Should i use some cookies or work with sessions? Please help me it's my university project... -
Django database update + celery recurrent task
I'm using django + celery and having some problems with concurrency. I have the following scenery: One endpoint that updates an object called Route and a celery task that runs each 5 seconds that do some actions based on that Route object data.. The problem is, sometimes the action from my endpoint happens so closely to the celery task execution that the object wasn't updated on the database yet resulting in wrong interpretation. I'm reading about atomic transactions but don't know for sure how to implement that in my case. Any suggestions? Thank you! -
How can i integrate spotify web api in my django web app to display tracks, artists and playlists
I am creating a web app for streaming and downloading music. I want to fectch tracks, albums and artists using spotify api and display them on my home page but my website keeps redirecting endlessly. please help, this is my code: import requests import spotipy.util as util import pylast import random import os def home(request): scope = 'user-library-read' # Authenticate the user token = util.prompt_for_user_token( username=None, scope=scope, client_id='beaf4d3d7ca34bceb485a30636dedcdf', client_secret=SPOTIPY_CLIENT_SECRET, redirect_uri='http://localhost:8888/home/', ) if token: sp = spotipy.Spotify(auth=token) # Get a random track track_results = sp.search(q='year:2022', type='track', limit=50, offset=0) random_track = random.choice(track_results['tracks']['items']) track_name = random_track['name'] track_artist = random_track['artists'][0]['name'] track_album = random_track['album']['name'] track_image = random_track['album']['images'][0]['url'] # Get a random album album_results = sp.search(q='year:2022', type='album', limit=50, offset=0) random_album = random.choice(album_results['albums']['items']) album_name = random_album['name'] album_artist = random_album['artists'][0]['name'] album_image = random_album['images'][0]['url'] # Get a random artist artist_results = sp.search(q='year:2022', type='artist', limit=50, offset=0) random_artist = random.choice(artist_results['artists']['items']) artist_name = random_artist['name'] artist_image = random_artist['images'][0]['url'] context = { 'track_name': track_name, 'track_artist': track_artist, 'track_album': track_album, 'track_image': track_image, 'album_name': album_name, 'album_artist': album_artist, 'album_image': album_image, 'artist_name': artist_name, 'artist_image': artist_image, } else: context = {} return render (request, 'search.html', context) #this is my urls.py: #urlpatterns = [ #path('home/', views.home, name='home'), #path('search/', views.search, name='search'), #] #but if i load the page it enters a redirect … -
JWT Token payload configuration sending more data fields than asked for?
I have to setup JWT token authentication for one of my projects. Lets call it project B which is a video conferencing project backend. The authentication needs to happen after connecting to Project A which is a Django rest api with all the users registered. My front end app will connect to Project A , get the payload and send the JWT to project B for authentication. For now project B requires only 2 data fields : "aud" : JWT_APP_ID "secret" : JWT_APP_SECRET The above 2 fields is what project B requires to authenticate and start the video conference. JWT_APP_ID & JWT_APP_SECRET are both entered on project A end and fetched by the front end app. However, at the risk of sounding stupid, can we send more than 2 fields i.e. more than what is asked for by project B? I have some important fields like call_duration, call_type(audio/video) which needs to be sent. Hopefully I will be able to send the data back through an event synch module plugin on project B end which saves them and transmits it back to my Django rest api for saving it in the database. -
sending websocket messages from my dockerized backend to my dockerized frontend
I'm sending websocket messages from an external script to a django page and it works fine until i dockerize it. my django page (my frontend) is running on port 80, and my frontends docker-compose states ports: - 80:80 hostname: frontend and my backend.py file is trying to connect with this line async with websockets.connect('ws://frontend:80/ws/endpoint/chat/', ping_interval=None) as websocket: so i think my backend should be able to see it. its able to connect when not dockerized with async with websockets.connect('ws://localhost:80/ws/endpoint/chat/', ping_interval=None) as websocket: the error i get when dockerized is Traceback (most recent call last): File "/usr/local/lib/python3.9/multiprocessing/process.py", line 315, in _bootstrap self.run() File "/usr/local/lib/python3.9/multiprocessing/process.py", line 108, in run self._target(*self._args, **self._kwargs) File "//./main.py", line 531, in send_SMS_caller asyncio.run(SendSMS()) File "/usr/local/lib/python3.9/asyncio/runners.py", line 44, in run return loop.run_until_complete(main) File "/usr/local/lib/python3.9/asyncio/base_events.py", line 647, in run_until_complete return future.result() File "//./main.py", line 496, in SendSMS async with websockets.connect('ws://frontend:80/ws/endpoint/chat/', ping_interval=None) as websocket: File "/usr/local/lib/python3.9/site-packages/websockets/legacy/client.py", line 637, in __aenter__ return await self File "/usr/local/lib/python3.9/site-packages/websockets/legacy/client.py", line 655, in __await_impl_timeout__ return await self.__await_impl__() File "/usr/local/lib/python3.9/site-packages/websockets/legacy/client.py", line 662, in __await_impl__ await protocol.handshake( File "/usr/local/lib/python3.9/site-packages/websockets/legacy/client.py", line 329, in handshake raise InvalidStatusCode(status_code, response_headers) websockets.exceptions.InvalidStatusCode: server rejected WebSocket connection: HTTP 404 chatgpt suggested i point to the specific ip of my hostmachine which i do … -
How to delete oldest data in table if more than 5 row using django?
If data in table more than 5 row I want to delete oldest row such as. id value 1 a1 <= delete 2 a2 3 a3 4 a4 5 a5 6 a6 I want to keep new 5 rows which is id 2-6 and delete oldest row which is id 1. I use this code. objects_to_keep = Data.objects.filter(key=key).order_by('id')[:5] Data.objects.exclude(pk__in=objects_to_keep).delete() It show error like this. NotSupportedError at /device/ (1235, "This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'") How to fix it? -
I was doing a "questions site" from the Django docs and I'm having a problem
There is problems i terminal and dashboard I want build quiz site with Django docs -
I deployed a Django project packaged with Zappa to AWS Lambda, but it always returns null
I'm trying to use a zip file created with zappa package instead of zappa deploy to match my CI/CD process. AWS Lambda settings: Runtime: Python 3.9 Handler: handler.lambda_handler Architecture: x86_64 When I access the HTTP endpoint, it always returns null in the browser. I created a Django project. It's a basic project, and you can check this project on the following GitHub repository. https://github.com/hongmingu/zappa1sample I used the zappa package dev command to create a zip file and uploaded it to S3. Then, I set the S3 URL as the source in AWS Lambda. Here's my zappa_settings.json file: { "dev": { "aws_region": "ap-northeast-2", "django_settings": "zappa1sample.settings", "project_name": "zappa1sample", "runtime": "python3.9", "s3_bucket": "lambda-saver12123" }, "production": { "aws_region": "ap-northeast-2", "django_settings": "zappa1sample.settings", "project_name": "zappa1sample", "runtime": "python3.9", "s3_bucket": "lambda-saver12123" } } AWS CloudWatch logs are as follows: INIT_START Runtime Version: python:3.9.v19 Runtime Version ARN: arn:aws:lambda:ap-northeast-2::runtime:e73d5f60c4282fb09ce24a6d3fe8997789616f3a53b903f4ed7c9132a58045f6 START RequestId: ae67fca5-6afa-4a2c-a920-2440bae5af2b Version: $LATEST Instancing.. [DEBUG] 2023-04-19T07:44:36.009Z ae67fca5-6afa-4a2c-a920-2440bae5af2b Zappa Event: {'version': '2.0', 'routeKey': '$default', 'rawPath': '/', 'rawQueryString': '', 'headers': {'sec-fetch-mode': 'navigate', 'x-amzn-tls-version': 'TLSv1.2', 'sec-fetch-site': 'cross-site', 'accept-language': 'ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7,ar;q=0.6,zh-CN;q=0.5,zh;q=0.4', 'x-forwarded-proto': 'https', 'x-forwarded-port': '443', 'x-forwarded-for': '222.111.140.167', 'sec-fetch-user': '?1', 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7', 'x-amzn-tls-cipher-suite': 'ECDHE-RSA-AES128-GCM-SHA256', 'sec-ch-ua': '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"', 'sec-ch-ua-mobile': '?0', 'x-amzn-trace-id': 'Root=1-643f9be1-1f1cb40742c78d566ab0c546', 'sec-ch-ua-platform': '"macOS"', 'host': 'wzzdsza2liopkemzy7h4q3okyu0gsusx.lambda-url.ap-northeast-2.on.aws', 'upgrade-insecure-requests': '1', 'accept-encoding': 'gzip, deflate, br', 'sec-fetch-dest': 'document', … -
How to only show related objects in Django Admin screens
I have an app where I want administrators to be able to create events via the admin view. I have members, who will have multiple cars and attend multiple meets. I want to record which vehicle they used at a meet. In the django admin view for a member, I can manage their cars successfully and only cars belonging to that member show up in the inline on the Member Admin page, but when attempting to manage meets, all cars are listed, not only cars belonging to that member. I want the same list of cars from the CarInline to appear in the MeetInline - i.e. cars registered to the member. Any ideas how to achieve this? I think that the issue is that the Meet model has a ManyToMany relationship with the Car model but wasn't sure how else to model this. models.py class Member(models.model): member_number = models.CharField(primary_key=True, max_length=30) is_active = models.BooleanField(default=True) class Car(models.model) member = models.ForeignKey(Member) registration = models.CharField(max_length=80) class Meet(models.model) meet_date = models.DateTimeField() member = models.ForeignKey(Member) car = models.ManyToManyField(Car) admin.py class CarInline(admin.TabularInline): model = Car extra = 0 fields = ["registration"] class MeetInline(admin.TabularInline): model = Meet extra = 0 fields =["meet_date", "car"] class MemberAdmin(admin.ModelAdmin): list_filter = [ … -
Django limit query not working in get_queryset
I overwrite get_queryset as below: def get_queryset(self, request): qs = super().get_queryset(request) qs.order_by('-id').all()[:3] print(qs) print() qs2 = CreditsTransaction.objects.all()[:3] print(qs2) return qs This is my output: [2023-04-19 08:53:52 +0000] [1178] [INFO] Booting worker with pid: 1178 <QuerySet [<CreditsTransaction: CreditsTransaction object (623267)>, <CreditsTransaction: CreditsTransaction object (623266)>, <CreditsTransaction: CreditsTransaction object (623265)>, <CreditsTransaction: CreditsTransaction object (623264)>, <CreditsTransaction: CreditsTransaction object (623263)>, '...(remaining elements truncated)...']> <QuerySet [<CreditsTransaction: CreditsTransaction object (623267)>, <CreditsTransaction: CreditsTransaction object (623266)>, <CreditsTransaction: CreditsTransaction object (623265)>]> So in qs.order_by('-id').all()[:3] the number of results is not limited to 3. Whereas in CreditsTransaction.objects.all()[:3] it is. I want to know why. -
ImportError: from django.conf import DEFAULT_STORAGE_ALIAS, settings
am trying to run my django app on local server and instead am getting this error: ImportError, cannot import name 'DEFAULT_STORAGE_ALIAS' from 'django.conf' -
python subprocess - google-chrome headless - self-signed certificate - screenshot
When opening a django shell: python manage.py shell and typing in: import subprocess command = [ f'google-chrome', '--headless=new', f'--screenshot=/home/user/tmp/screen.png', f'--window-size={800,1700}', '--no-first-run', '--allow-http-screen-capture', '--force-device-scale-factor=1', '--ignore-certificate-errors', '--ignore-urlfetcher-cert-requests', '--disable-test-root-certs', '--allow-running-insecure-content', '--hide-scrollbars', '--allow-insecure-localhost', '--disable-system-font-check', '--disable-gpu', '--disable-extensions', '--disable-dev-shm-usage', '--disable-software-rasterizer', '--disable-notifications', '--user-data-dir=/tmp/chromium-home', '/home/user/tmp/screen.html', ] subprocess.run(command, **{}) The console output is the following: [32873:32901:0419/083534.872076:ERROR:bus.cc(399)] Failed to connect to the bus: Failed to connect to socket /run/user/0/bus: Permission denied [32873:32901:0419/083534.884135:ERROR:bus.cc(399)] Failed to connect to the bus: Failed to connect to socket /run/user/0/bus: Permission denied [32873:32901:0419/083534.970536:ERROR:bus.cc(399)] Failed to connect to the bus: Failed to connect to socket /run/user/0/bus: Permission denied [32873:32901:0419/083534.970630:ERROR:bus.cc(399)] Failed to connect to the bus: Failed to connect to socket /run/user/0/bus: Permission denied (process:32873): dconf-CRITICAL **: 08:35:35.289: unable to create directory '/run/user/0/dconf': Permission denied. dconf will not work properly. (process:32873): dconf-CRITICAL **: 08:35:35.314: unable to create directory '/run/user/0/dconf': Permission denied. dconf will not work properly. (process:32873): dconf-CRITICAL **: 08:35:35.350: unable to create directory '/run/user/0/dconf': Permission denied. dconf will not work properly. [32873:32899:0419/083537.631303:ERROR:cert_verify_proc_builtin.cc(679)] CertVerifyProcBuiltin for 127.0.0.1 failed: ----- Certificate i=0 (<snip>) ----- ERROR: No matching issuer found [32873:32897:0419/083537.639022:ERROR:cert_verify_proc_builtin.cc(679)] CertVerifyProcBuiltin for 127.0.0.1 failed: ----- Certificate i=0 (<snip>) ----- ERROR: No matching issuer found 572051 bytes written to file /home/user/tmp/screen.png CompletedProcess(args=['google-chrome', '--headless=new', '--screenshot=/home/user/tmp/screen.png', '--window-size=(800, 1700)', '--no-first-run', '--allow-http-screen-capture', '--force-device-scale-factor=1', '--ignore-certificate-errors', '--ignore-urlfetcher-cert-requests', … -
Flowbite component not working when loaded via HTMX (Django project)
For my Django application I am using Flowbite to make interactive UI components. I am also using HTMX to dynamically load some html content from the back-end (Django) into the page without refresh. Basically I have a button that sends a HTMX get requests to the backend and then targets a modal window (a Flowbite component) with the received html (nothing ground-breaking). The mechanism works well, however here is the twist: the html code that my backend returns, contains another Flowbite component i.e. a dropdown menu. <!-- MODAL BTN --> <button hx-get="{% url '<myurl>' %}" hx-target="#newItemModal" data-modal-target="newItemModal" data-modal-toggle="newItemModal" class="block text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center" type="button"> Modal open </button> <!-- MODAL WINDOW --> <div id="newItemModal" tabindex="-1" aria-hidden="true" class="fixed top-20 left-0 right-0 z-50 hidden w-full p-4 overflow-x-hidden overflow-y-auto md:inset-0 h-[calc(100%-1rem)] md:h-full"> </div> The HTML returned by the backend with the hx-get is as follows: <div> ... <!-- MENU BTN --> <button type="button" data-dropdown-toggle="dropdownEditMenu" class="aspect-square h-10 ml-2 rounded-lg text-white drop-shadow-[0_1.2px_1.2px_rgba(0,0,0,0.8)] hover:text-slate-100"> <span class="mdi mdi-dots-vertical text-3xl"></span> </button> <!-- DROPDOWN MENU --> <div id="dropdownEditMenu" class="z-10 hidden rounded-lg shadow w-48 max-h-48 lg:max-h-none bg-slate-600 overflow-auto"> <ul class="text-sm text-white"> <li class="hover:bg-slate-700 px-4 py-2 truncate"> <a href="{% url <myurl> %}" class="w-full inline-flex … -
Django ModelAdmin/ModelForm readonly permissions flow
I have a Django admin application and I have a particular issue with one of the admin pages. I have a model which looks like this. class Quote(CommonModel, models.Model): amount = models.IntegerField(blank=True, null=True, verbose_name="Approved credit amount") The form looks like this: class QuoteForm(django.forms.ModelForm): amount = django.forms.CharField(widget=django.forms.TextInput()) and the ModelAdmin looks like this: class QuoteAdmin(admin.ModelAdmin): form = QuoteForm Now I need to amend this amount to format it so that it reads in dollars and cents from the int value in the database, this is not an issue in the form when the user has change permissions to the ModelAdmin, I have ammended the form to look like this: class QuoteForm(django.forms.ModelForm): amount = django.forms.CharField(widget=django.forms.TextInput()) def clean_approved_amount_amount(self, value: str): return self.convert_string_float_dollar_representation_to_cent_integer( self.cleaned_data['approved_amount_amount'] ) def __init__(self, *args, **kwargs): super(QuoteForm, self).__init__(*args, **kwargs) self.initial['amount'] = kwargs['instance'].integer_values_in_dollar_format(kwargs['instance']['amount']) But if the user only has read only permissions to the ModelAdmin the form flow is different and fails and I can't seem to figure out when the ModelAdmin picks up that the form is readonly so that I can convert the value in the DB to a dollar and cent amount. There is no documentation on this conditional flow that I can find to understand when I should …