Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django is supporting optional params in routes? [duplicate]
I've spend lot of time to find out how to create an url with optional params but I didn't find anything. I'm working wiht Python 3.4 This is my path and just I need to add an optional param: path('request', request_view.index, name="request_index"), Somthing like this one (like other lenguages): path('request/?status', request_view.index, name="request_index"), Any help? -
django: create user account for online shopping
I am developing an online ordering web, where user can place order by filling forms. After order is submitted, user can log in the account to view his own order information and status. My problem is, how to create such user account model and user account page that allow user to view only their orders? is there any good example and built-in functions available? -
how to integrate customizable bootstrap in Django
I am trying to add bootstrap files so that I can edit custom Saas. for the past 2 days I've been looking here and there but didn't seem to find the correct way, I have tried Webpack but that was too complex and it downloaded a lot of extra files that were not needed, I have tried installing via parcel, followed the official bootstrap documentation but didn't know how to integrate it with Django static files. I can not use cdn because I heard then you cant customize Saas. I have searched on youtube, but could not get 1 simple way. can you guys suggest me docs or video that provide a simple way so that I can customize Saas in my own way. i have researched alot. thank you -
Django: I have a TextField which when having text entered into it is also saving the html inputs
I am trying to get my HTML to return the information written to TextField, when the information is submitted and rendered instead of being seen in the expected format every new line the text would be on is appearing inside the angled paragraph brackets. can anyone help me understand why the text is being displayed like this, please? -
Steam social login with Django backend and React frontend
I have created a steam login with python-social-auth library on the backend. That was working fine. Now I am trying to separate my backend from the frontend using React for the frontend and Django for the backend. I can't seem to figure out or find anything on how do I connect the social login from React? I have followed this tutorial to do it which uses drf-social-oauth2-library but he is using a react-facebook-login package to make the login and retrieve the access token and refresh token for which I did not find anything similar for steam. I am really lost in here to what to do or how to go about it as I am quite new to both React and Django. -
Is it Apache 2.2 compatible with django3.2 and python 3.9?
Is it Apache 2.2 compatible with django3.2 and python 3.9? we have Apache 2.2 server needs to deploy python version 3.9 and Django 3.2. -
Django: Link to ForeignKey from change page
Imagine there are models: from django.db import models class Category(models.Model): name = models.CharField(...) class Product(models.Model): name = models.CharField(...) category = models.ForeignKey(Category, ...) Register models: from django.contrib import admin @admin.register(Product) class ProductAdmin(admin.ModelAdmin): fields = 'name', 'category', How could I make a category in product change page in admin to be a link to category by some built-in instruments? P.S. Well there is a package django-admin-relation-links. -
Django Rest Framework custom serializer data
I got a serializer response that looks like this: "results": [ { "property_name": "Villa", "username": "Ivan", "email": "ivan@mail.com", "start_date": "2022-01-05", "end_date": "2022-01-19" }, { "property_name": "Villa", "username": "Ivan", "email": "ivan@mail.com", "start_date": "2022-02-16", "end_date": "2022-03-03" }, { "property_name": "Villa", "username": "Ivan", "email": "ivan@mail.com", "start_date": "2022-02-11", "end_date": "2022-02-25" } ] I wonder is it possible for the serializer response to look like this: [ { name: 'Ivan', email: 'ivan@mail.com', stays: [ { "start_date": "2022-01-05", "end_date": "2022-01-19", "property_name: Villa" }, { "start_date": "2022-02-16", "end_date": "2022-03-03", "property_name: Villa" }, { "start_date": "2022-02-11", "end_date": "2022-02-25", "property_name: Villa" }, ] } ] This is my model: class PropertyReservation(BaseModelFields): start_date = models.DateField() end_date = models.DateField() property = models.ForeignKey('property.Property', on_delete=models.CASCADE) user = models.ForeignKey('user.UserModel', on_delete=models.CASCADE) my serializer: class PropertyReservationGuestSerializer(serializers.ModelSerializer): property_name = serializers.ReadOnlyField(source='property.name') username = serializers.ReadOnlyField(source='user.username') email = serializers.ReadOnlyField(source='user.email') class Meta: model = PropertyReservation fields = ('property_name', 'username', 'email', 'start_date', 'end_date') I tried a few things and cant manage the serializer response to look like one in the example above. This was the best answer I found on the internet Django RestFramework group by and still was not able to do it, on the first solution I got an error when I call the super() function: "super(type, obj): obj must … -
Putting "test" in URL breaks dispatcher in django [closed]
This is more a 'hmm' question rather than an "I need help" one So I have a URL like so: path('<str:movie>', views.movies, name='movies') The URL works just fine when I go to /movies/test-movie, but not movies/test or movies/bro Is there a certain reason why these URLs don't work? Thanks! -
How to use chained django_select2 selects in django admin panel?
I took almost unchanged guide from documentation there is my models.py from django.db import models class Country(models.Model): name = models.CharField(max_length=255) class City(models.Model): name = models.CharField(max_length=255) country = models.ForeignKey('Country', related_name="cities", on_delete=models.CASCADE) class Address(models.Model): country = models.ForeignKey('Country', on_delete=models.CASCADE) city = models.ForeignKey('City', on_delete=models.CASCADE) and have created ModelForm because simple Form from documentation guide is not fits for admin panel class AddressForm(forms.ModelForm): class Meta: model = Address fields = '__all__' widgets = { 'country': ModelSelect2Widget( model=Country, search_fields=['name__icontains'], ), 'city': ModelSelect2Widget( model=City, search_fields=['name__icontains'], dependent_fields={'country': 'country'}, max_results=500, ) } on the simple, not admin, page it works fine. I tried it just for testing. I really need only in admin panel. here is the template from docs <!DOCTYPE html> <html lang="en"> <head> <title>Create Book</title> {{ form.media.css }} <style> input, select {width: 100%} </style> </head> <body> <h1>Create a new Book</h1> <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit"> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> {{ form.media.js }} </body> </html> and view class class AddressCreateView(generic.CreateView): model = models.Address form_class = forms.AddressForm success_url = "/" template_name = 'address.html' But in the admin panel the same form is not works. Selects does not containing any items and there is no search field shown there is also no requests sent to the … -
my edit page showing nothing besides what already in the main.html
I'm working on a Django project making a to-do list app in my edit page nothing is showing besides what is already inside my main.html my edit.html file {% extends 'main.html' %} {% block container %} <div>editor</div> <div> {% if item %} <form class="form-check-inline my-2 my-lg-0" method="POST"> {% csrf_token %} <input class="form-control mr-sm-2" type="search" placeholder="{{ item.item }}" aria-label="search" value="{{ item.item }}" name="item"> <input type="hidden" value="{{item.complete}}" name="complete"> <button clss="btn btn-outline-sceondary my-2 my-sm-0" type="submit">Submit</button> </form> {% endif %} </div> {% endblock %} my views def edit(request, list_id): if request.method == "POST": item = List.objects.get(pk=list_id) form = ListForms(request.POST or None, instance=item) if form.is_valid(): form.save() messages.success(request,('Item has been Edited')) return redirect('home') #return render(request, 'home.html',{'all_item': all_item}) else: item = List.objects.get(pk=list_id) return render(request, 'home.html',{'item': item}) my URLs from django import views from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('delete/<list_id>', views.delete, name='delete'), path('crossoff/<list_id>', views.crossoff, name='crossoff'), path('uncrossoff/<list_id>', views.uncrossoff, name='uncrossoff'), path('edit/<list_id>', views.edit, name='edit'), ] if you need any more information just ask me in the comment -
Host a Django project on Apache2 locally
I have finished a Django project and want to deploy it over Apache2 locally over LAN. I have figured out how to connect Django with Apache2 using mod_wsgi and it worked great because I was able to use Apace2 to actually host Django on localhost. Now I want to actually make this project available to anyone on my local network. Like for instance assuming that my local IP address was 10.10.10.51 I could go to a different device connected to my local network and type in 10.10.10.51 to actually get to the Apache2 server homepage. It does that successfully. My Django project is hosted on my Apache2 localhost server at djangoproject.localhost and it works fine just on my PC. When I move on to the other PC and go to djangoproject.localhost the site is not up there. Yes they are both connected to the same LAN network. I used this tutorial to host Django on Apache2: Host Django on Apache2 with mod_wsgi -
Why django can't read my path url to show the book list?
I made some objects on my local library site and trying to go in this link: catalog/books/ to see my Booklist, but the result: enter image description here also my codes : urls.py: from django.urls import path from django.contrib import admin from . import views app_name='catalog' urlpatterns = [ path(r'^$', views.Index.as_view(), name='index'), path(r'^books/$', views.BookListView.as_view(), name='books'), path(r'^book/(?P<pk>\d+)$', views.BookDetailView.as_view(), name='book-detail'), ] my html files: enter image description here enter image description here also i add catalog: in my models in def get_absolute_url -
Django: How i can dislay the resulat of some calculation after press a button on the same page
i want to display the result of some calculation after click on a button, the thing that I have go and call the fields-calculated after calculation in the same template html. but the result is gone to another page because i have specified on the urls.py another route url. Here is the code of the 2 functions: one is for calculation and the other one is for the home page (where is contain the fields-data that i have entered and the button of calculation), and i want to display there the result of calculation that i have did on the first function in the views.py: @login_required def calcul_resultat(request): resultat = float(0) ch_permanent = request.POST.get('ch_permanent', False) ch_exp = request.POST.get('ch_exp', False) calcul="" calcul_exp="" calcul_md="" if not (ch_permanent and ch_exp): return HttpResponse({"result" :resultat}) else: float_ch_exp = float(ch_exp) resultat = 2.4 * float_ch_exp calcul += "<strong>Calculation of Dweight: </strong>" calcul += str(resultat) float_ch_permanent = float(ch_permanent) resultat = 3.6 * float_ch_permanent calcul_exp += "<strong>Calculation of the load: </strong>" calcul_exp += str(resultat) float_calcul_exp = float(2.4 * float_ch_exp) float_calcul_per = float(3.6 * float_ch_permanent) float_length = float(length) resultat += (float_calcul_exp * float_length) calcul_md += "<strong>Calculation moment </strong>" calcul_md += str(resultat) return render(request,'pages/home.html',{'calcul':calcul, 'calcul_exp':calcul_exp, 'calcul_md':calcul_md}) and Here it is … -
Django GeoIP2 libmaxmind c library in a docker container
I use GeoIP2 in a dockerised Django app and am looking to improve the performance of the IP lookups. The Django documentation says: Additionally, it is recommended to install the libmaxminddb C library, so that geoip2 can leverage the C library’s faster speed. Could somebody please provide a working example of how to do this in a docker container? I am using a Django Cookiecutter template, which uses docker-compose and a python image in the Django Dockerfile: ARG PYTHON_VERSION=3.9-slim-bullseye FROM python:${PYTHON_VERSION} as python FROM python as python-build-stage ARG BUILD_ENVIRONMENT=local I'm currently using GeoIP2 like this in views.py, and it does not perform well: from django.contrib.gis.geoip2 import GeoIP2 from ipware import get_client_ip class CheckInView(View): def get(self, request, pk): if client_ip and is_routable: client_ip, is_routable = get_client_ip(request) g = GeoIP2() city_dict = g.city(checkin.ip) checkin.city = city_dict['city'] checkin.post_code = city_dict['postal_code'] checkin.region = city_dict['region'] checkin.country_code = city_dict['country_code'] checkin.country_name = city_dict['country_name'] lat_lon = g.lat_lon(client_ip) checkin.lat = lat_lon[0] checkin.lon = lat_lon[1] ... return HttpResponseRedirect(...) I'm requesting a working example because there is a lot I don't know: not familiar with compiling stuff in c, not familiar with how to use c from python, and definitely not familiar with how to do these things inside a docker … -
Django Registration - Checks if a user already exists
The web app currently should be able to register new users. However, should a user already exists, it should redirect user to the login page with a message of "User already exists!". The Django views: def registerPage(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] username = form.cleaned_data['username'] if User.objects.filter(username=username).exists(): messages.info( request, 'User already exists! Try logging in.') return redirect('login') else: user = form.save(commit=False) raw_password = User.objects.make_random_password() user.set_password(raw_password) user.save() ... I filter the user by his/her username and checks if it already exists by using the exists() method. This doesn't seem to work though. Is there something I'm missing? -
how to setup liveness model in face recognition employee attendance system ---python
I am new to programming and, I am building a real-time face recognition employee attendance system for a company in python, but I can not set up the liveness model(anti-spoofing), how can I do that pls help me thank you all, here below is code for face detecting during check-in time def mark_your_attendance(request): detector = dlib.get_frontal_face_detector() predictor =dlib.shape_predictor('face_recognition_data/shape_predictor_68_face_landmarks.dat') svc_save_path="face_recognition_data/svc.sav" with open(svc_save_path, 'rb') as f: svc = pickle.load(f) fa = FaceAligner(predictor , desiredFaceWidth = 96) encoder=LabelEncoder() encoder.classes_ = np.load('face_recognition_data/classes.npy') faces_encodings = np.zeros((1,128)) no_of_faces = len(svc.predict_proba(faces_encodings)[0]) count = dict() present = dict() log_time = dict() start = dict() for i in range(no_of_faces): count[encoder.inverse_transform([i])[0]] = 0 present[encoder.inverse_transform([i])[0]] = False vs = VideoStream(src='http://192.168.137.127:8080/video').start() sampleNum = 0 while(True): frame = vs.read() frame = imutils.resize(frame ,width = 800) gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = detector(gray_frame,0) for face in faces: print("INFO : inside for loop") (x,y,w,h) = face_utils.rect_to_bb(face) face_aligned = fa.align(frame,gray_frame,face) cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),1) (pred,prob)=predict(face_aligned,svc) if(pred!=[-1]): person_name=encoder.inverse_transform(np.ravel([pred]))[0] pred=person_name if count[pred] == 0: start[pred] = time.time() count[pred] = count.get(pred,0) + 1 if count[pred] == 4 and (time.time()-start[pred]) > 1.2: count[pred] = 0 else: #if count[pred] == 4 and (time.time()-start) <= 1.5: present[pred] = True log_time[pred] = datetime.datetime.now() count[pred] = count.get(pred,0) + 1 print(pred, present[pred], count[pred]) cv2.putText(frame, str(person_name)+ str(prob), (x+6,y+h-6), cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,255,0),1) … -
Django Rest Framework Am I doing it right?
I have studied DRF myself and one question bothers me, unfortunately I have no one to ask and this question bothers me all the time. Is writing application logic in views (as in the attached code) a good approach? When sending a query to the server with the intention, for example, to accept an order, I have to update the values from models other than the order or carry out validation of statuses, change the data on their basis. In the first tutorials from which I learned, among others, JustDjango all logic is in the view. However, after writing some code and watching other tutorials, I feel that this is not the right approach. Should not save and update models be done through a serializer? If so, whether through one large serializer or several smaller serializers. class ZK_AddUpdateItemWithInstaReservation(APIView): permission_classes = (IsAuthenticated,) def post(self, request, *args, **kwargs): pzitem_id = request.data.get('pzitem_id') ordered_quantity = request.data.get('ordered_quantity') order_id = request.data.get('order_id') user_id = request.data.get('user_id') item_id = request.data.get('item_id') if ordered_quantity: if int(ordered_quantity) < 0: return Response({'error': 'Próbujesz zamówić ujemną wartość'}) try: item = Item.objects.get(id=item_id) except: return Response({'error': 'Item with given id does not exists'}) try: order = Order.objects.get(id=order_id) except: return Response({'error': 'Order with given id does not … -
Add filters to autocomplete fields in django
I have a question about autocomplete fields in django. Let's assume we have these 2 models: class Animal: name = models.CharField() is_big = models.BooleanField() class Human: pet = models.ForeignKey(Animal) And then we have the admin file which looks something like this: class HumanAdmin(admin.ModelAdmin): autocomplete_fields = ['pet'] def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'pet': kwargs["queryset"] = Animal.objects.filter(is_big=True) return super().formfield_for_foreignkey(db_field, request, **kwargs) class AnimalAdmin(admin.ModelAdmin): search_fields = ['name'] admin.site.register(Animal, AnimalAdmin) admin.site.register(Human, HumanAdmin) What I wanted to achieve here is to have in the animal selection dropdown only the big animals which worked, and then I decided to make that filed an autocomplete one but after making it autocomplete it seems to be ignoring my formfield_for_foreignkey filter, it is now loading all the animals. And I wanna ask how should I combine these two properly? I want an autocomplete field for animals, but I want it to consider only those who have is_big == True . My idea is that I should somehow capture what is entered on the autocomplete textfield and add that to my filtering but I'm not sure how to do that. -
How do I livestream the video I have captured using OpenCV on my webpage which is made using Django while also keeping the face recognition function
I am a new developer working at an interI am developing a web application which takes your attendance using face recognition and puts the entry in the database using django, python, open-cv and the face_recognition library of python. The Login page looks like this: Login Page. When I click the login button, my views program directs to an external python function which opens a separate camera window which does the face recognition. The Camera Window. What I want to do is display the camera directly in the browser window rather than as a separate window. I found some tutorials and also tried to implement them but using them I can only display the frames in the browser window while the functionality of face recognition is lost. The Views Code (views.py): def camera_on(request): out = Popen('E:/Study/Internship/Capstone/Project/Web App/web_app/Basic.py', shell=True, stdout=PIPE) op = out.stdout.read().decode("utf-8") new_str = '' for i in range(len(op)-2): new_str += op[i] request.session['name'] = new_str return render(request, 'open_camera.html', {'data': new_str}) This code accesses the Basics.py file which opens the camera window, does the face recognition and gives the entry in the database. The Basics.py code: from datetime import datetime, date import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'web_app.settings') django.setup() import cv2 import face_recognition … -
How to display choices in a django form based on a database
I am writing a django application that helps create a shopping list based on the store stock. The store stock will be stored as a database that looks like this (please ignore spelling errors!): Type Name Colour Fruit Apple Pink Fruit Apple Green Fruit Banana Yellow Fruit Banana Green Fruit Clementine Orange Fruit Blueberry Blue Veg Tomato Red Veg Spinach Dark green Veg Kale Dark green Veg Dwarf beans Light green From this store stock, a user can create a shopping list by choosing the above three fields using a form. The user will first choose the type - which should be displayed as a choice between "Fruit" or "Veg". Then when they choose "Fruit" for example, only the fruits should be provided as choices in "Name". Finally, for them to choose colour, only the corresponding colour of the chosen fruit should be displayed as the options in the form. To create the store stock database, the form I created is as follows: Class Stock(models.Model): Type_choices = models.TextChoices('Fruit','Veg') stock_type = models.CharField(choices=Type_choices.choices) name = models.CharField(max_length=264, unique=False) colour = models.CharField(max_length=264, unique=False) I then populated it to look like the above table. To store the shopping list, I created a model: Class ShoppingList(models.Model): … -
Render seaborn Plot on Django Template
I am trying to render the plot generated by seaborn on Django template. I have the following code in my views.py: import matplotlib.pyplot as plt import seaborn as sns from io import BytesIO import base64 def heat_map_plot(): df = data.corr() plot = sns.heatmap(data=df) buffer = BytesIO() plot.savefig(buffer, format='png') graphic = base64.b64encode(buffer.getvalue()) return graphic in stats.html: <li><img src='data:image/png;base64,{{heat_map_plot}}'/></li> but show empty png in the template, why? -
How to add extra key in created object in Django Rest Framework?
I'm new to Django Currently I'm trying to add a simple extra key on my returned json in the serializer. Here's the create() override of my serializer: def create(self, validated_data): available_dates = validated_data.pop("available_dates") # Default expiry time is 3 days expiry = datetime.datetime.now() + datetime.timedelta(days=3) event = Events.objects.create(**validated_data, expiry=expiry) for selectedTime in available_dates: AvailableDates.objects.create( event=event, **selectedTime, ) signer = Signer() signedObject = signer.sign_object( {"expiry": expiry.isoformat(), "id": event.id} ) return {**event, "signed_url": signedObject} As you can see, I don't want to only return event, but I want to add a signed url. This gave me an error: 'Events' object is not a mapping So then how do I add extra key? What do I return in the create function? Can I create Response() as the return of create function in DRF? -
Installing mod_wsgi with pip install causes an error
I am trying to install mod_wsgi so I can run my Django app with Apache. However when I use pip install mod_wsgi I get the following error: ERROR: Command errored out with exit status 1: command: 'C:\Program Files\Python310\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-_w59fztq\\mod-wsgi_5a0ae0135da94aadbb09b85297022451\\setup.py'"'"'; __file__='"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-_w59fztq\\mod-wsgi_5a0ae0135da94aadbb09b85297022451\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Admin\AppData\Local\Temp\pip-record-mwvtbeia\install-record.txt' --single-version-externally-managed --user --prefix= --compile --install-headers 'C:\Users\Admin\AppData\Roaming\Python\Python310\Include\mod-wsgi' cwd: C:\Users\Admin\AppData\Local\Temp\pip-install-_w59fztq\mod-wsgi_5a0ae0135da94aadbb09b85297022451\ Complete output (24 lines): running install running build running build_py creating build creating build\lib.win-amd64-3.10 creating build\lib.win-amd64-3.10\mod_wsgi copying src\__init__.py -> build\lib.win-amd64-3.10\mod_wsgi creating build\lib.win-amd64-3.10\mod_wsgi\server copying src\server\apxs_config.py -> build\lib.win-amd64-3.10\mod_wsgi\server copying src\server\environ.py -> build\lib.win-amd64-3.10\mod_wsgi\server copying src\server\__init__.py -> build\lib.win-amd64-3.10\mod_wsgi\server creating build\lib.win-amd64-3.10\mod_wsgi\server\management copying src\server\management\__init__.py -> build\lib.win-amd64-3.10\mod_wsgi\server\management creating build\lib.win-amd64-3.10\mod_wsgi\server\management\commands copying src\server\management\commands\runmodwsgi.py -> build\lib.win-amd64-3.10\mod_wsgi\server\management\commands copying src\server\management\commands\__init__.py -> build\lib.win-amd64-3.10\mod_wsgi\server\management\commands creating build\lib.win-amd64-3.10\mod_wsgi\docs copying docs\_build\html\__init__.py -> build\lib.win-amd64-3.10\mod_wsgi\docs creating build\lib.win-amd64-3.10\mod_wsgi\images copying images\__init__.py -> build\lib.win-amd64-3.10\mod_wsgi\images copying images\snake-whiskey.jpg -> build\lib.win-amd64-3.10\mod_wsgi\images running build_ext building 'mod_wsgi.server.mod_wsgi' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ ---------------------------------------- ERROR: Command errored out with exit status 1: 'C:\Program Files\Python310\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-_w59fztq\\mod-wsgi_5a0ae0135da94aadbb09b85297022451\\setup.py'"'"'; __file__='"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-_w59fztq\\mod-wsgi_5a0ae0135da94aadbb09b85297022451\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; … -
How to disable specific change_actions button in Django admin?
I have a set of change_actions buttons on my Django Admin page: A part of code for this particular InvoiceAdmin page: def invoice_lines_link(self, request, obj): """ Set a button to the page of the Invoice's Invoice lines in the details view """ return HttpResponseRedirect("{url}?invoice__pk={pk}".format( url=reverse("admin:backend_invoiceline_changelist"), pk=obj.pk )) invoice_lines_link.label = "Invoice Lines" def customer(self, request, obj): """ Set a button to the page of the InvoiceLine's Customer in the details view """ return HttpResponseRedirect(reverse( "admin:backend_customer_change", args=[obj.customer.id] )) change_actions = ('customer', 'invoice_lines_link', 'test_link', 'pdf',) I would like to have a button disabled, when other action in called. How can i refer to that button and disable it? It is not in a form and not marked as a action, so both get_form() and admin.site.disable_action wont work. (I want to disable one of the grey buttons, that you can notice on the picture - it is not related to the form)