Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: module 'razorpay' has no attribute 'Client'
I'm using pipenv --python 3.6 environment and I installed razorpay(1.2.0) and all requirements but I still getting this error. when I click on submit button this error shows up. views.py file: if request.method == "POST": name = request.POST['name'] amount = request.POST['amount'] client = razorpay.Client(auth=("My-key-id", "My-secret-key")) # client.set_app_details({"title" : "django", "version" : "3.2.3"}) payment = client.order.create({'amount' : amount, 'currency' : 'INR' , 'payment_capture' : '1'}) print(payment) coffee = Coffee(name=name, amount=amount, payment_id=payment['id']) data = { payment : payment } return render(request, 'razorpay/donate_page.html', data) donate_page.html file: <div class="row"> <div class="col-md-6 "> <img src="{% static './assets/images/coffee-bg.png' %}" class="img-fluid" alt="img"> </div> <form method="POST" action="{% url 'donate_page' %}" class="col-md-5 offset-1"> {% csrf_token %} <div class="form-group"> <input name="name" type="text" class="form-control" placeholder="Name"> <small id="nameHelp" class="form-text text-muted">Enter the correct name, so that we will help you in case of donation-related problems.</small> </div> <div class="form-group"> <input name="amount" type="text" class="form-control" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 49 && event.charCode <= 57" placeholder="Enter amount"/> </div> <button type="submit" class="btn btn-success form-btn w-100 mt-3 mb-3">Donate</button> </form> </div> </main> {% if payment %} {% csrf_token %} <form action="{% url 'success' %}" method="POST"> <script src="https://checkout.razorpay.com/v1/checkout.js" data-key="My-key-id" // Enter the Test API Key ID generated from … -
How to set custom Django CMS
How to set a custom/editable sitename and site discription in Django CMS. The sitename and discription should be editable via Django CMS! Check the image -
django db ProgrammingError
When i try to reset database (i created a new empty database) i got this error when i run this command python manage.py makemigrations (or migrate) django.db.utils.ProgrammingError: HATA: "app_modelname" object doesnt exist LINE 1: ...", "app_modelname"."field1" FROM "field_2... i deleted all migration files in all apps (without __init__ ) and also .pyc files is there any idea for this problem? -
IntegrityError and NOT NULL constraint failed Like and Dislike Functionality
I'm trying to add like and dislike functionality to my application. I know there are lots of references I've checked them I was trying by myself. I've managed to add like and dislike in the database I've failed to retrieve and also I cannot redirect the same page. Please check my code and tell me how to solve this issue. I want to redirect to the post_detail page. I checked that I'm failed to add count_likes values to the Post model Post Model likes = models.IntegerField(default=0) PostLike Model class PostLike(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) def __str__(self): return self.post class Meta: unique_together = ("user", "post") HTML page <a href="#" onclick="document.getElementById('likebutton').submit()" > <div class="ui labeled button" tabindex="0"> <div class="ui red button comment"> <i class="heart icon"></i> Like </div> <a class="ui basic red left pointing label"> {{single_post.likes | intcomma}} </a> </div> </a> <form id="likebutton" action="{% url 'like_or_dislike_post' single_post.slug %}" method="POST"> {% csrf_token %} <input type="hidden"> </form> Urls.py file urlpatterns = [ path('category/<slug:category_slug>/<slug:post_slug>', views.post_detail , name="post_detail"), path('like_post/<slug:post_slug>', views.like_or_dislike_post, name="like_or_dislike_post"), ] Views.py file def like_or_dislike_post(request, post_slug): if request.method == 'POST': each_post = get_object_or_404(Post, slug=post_slug) try: liked_post = PostLike.objects.filter(user = request.user, post = each_post) if liked_post: liked_post.delete() count_like = PostLike.objects.filter(post = each_post).count() post_page … -
Use Hyperlink and Image in a Email-friendly way
Hey almighty Stackoverflow, i'm pretty new to Django and i'm required to write an HTML-Email Template, which includes Social-Media Icons that are also Hyperlinks. It all works fine in Preview, but when send by Email only the "Broken-Image"-icons appear. The Images are located in the static file of the Django Module and also in the static.dist directory of the main application. A few weeks ago, it worked, but after some pause and new testing yesterday, the images are broken. {% static 'ner_mail/YouTube.png' as yt_icon %} {% with 'target="blank" href="https://www.youtube.com/URL"'|safe as a_attr %} {% blocktrans %} <a {{ a_attr }} > <img src="{{ yt_icon }}" alt="" style="alignment: left;vertical-align:middle; width: 30px; padding-right: 5px" ></a> <a {{ a_attr }}> Social Media {% endblocktrans %} {% endwith %}</li> Can somebody maybe help me? Thank you in advance for any help! Best regards, -
Cannot get data of logged in User in Django
Respect for everyone here. I have CustomUser model from one app, and Field model from another app. And I put a connection in CustomUser model with Field model via ManyToMany. Field is for interested fields, and in signup form I have input like "In What do you have interests?" I can easily get other datas like username, date_of_birth, email... But cannot get this interests. It returns courses.Field.None Here is the models.py from django.db import models from django.contrib.auth.models import AbstractUser from courses.models import Field class CustomUser(AbstractUser): username = models.CharField(max_length=32 , verbose_name="Login", unique=True, ) first_name = models.CharField(max_length=64, verbose_name="Ismingiz", blank=False, null=False) second_name = models.CharField(max_length=64, verbose_name="Familyangiz", blank=False, null=False) # & dob = date of birth dob = models.DateField(auto_now_add=False, verbose_name="Yoshingiz", blank=False, null=True) gender_choices = [("e", "Erkak"), ("a", "Ayol")] gender = models.CharField(choices=gender_choices, verbose_name="Jinsingiz", default="e", max_length=1) -> interests = models.ManyToManyField(Field, verbose_name="Qiziqishlaringiz") longitude = models.CharField(max_length=256, verbose_name="Yashash joyingiz (uzunlik)", null=True, blank=True) latitude = models.CharField(max_length=256, verbose_name="Yashash joyingiz (kenglik)", null=True, blank=True) And this is my views.py file from courses App from django.shortcuts import render from .models import Center from .serializers import CenterSerializer, UserSerializer from rest_framework import generics from django.contrib.auth import get_user_model from rest_framework.response import Response from decimal import Decimal from slugify import slugify import operator from rest_framework.decorators import api_view ... other … -
Display users without a group in a template Django
I am creating an app that allows me to edit users on the frontend. Before doing this I wish to have all the users listed in a page. They are categorized by their group. Users that are in a group show up how they are supposed to. I want to also display users that are not in a group. This is how I fetch the users in a specific group: groupuser = User.objects.filter(groups__name='mygroup'). How do I display a user without any group in my template? I am new to Django and don't know much about this. -
I am making an affiliate website where we can copy product link and share it in other medias. please help to get me with it with a little idea
This is the product page. I have highlighted the portion of which i want to convey about. Here, in the 'Get Link' option i want to create a link for this product so that if a user copes and shares it to other media, it will open this page. P.S: Project is still in development -
How to run node and django server at a time
I am making a video chatting application in which I will use web sockets from npm and I have written WebSocket related code in a server.js file like this var webSocketServ = require('ws').Server; var wss = new webSocketServ({ port: 8000 }) var users = {}; var otherUser; wss.on('connection', function (conn) { console.log("User connected"); conn.on('message', function (message) { var data; . . . and so on and for managing URLs I used Django, so my problem is when I use python manage.py runserver, server.js is not running and application is not connecting to the server and if I run "node server.js" application is connecting to server but I am unable to manage URL as in Django code so I opened two instances of terminals and ran node in one terminal and python in another but I know its not the correct way and it won't be efficient while hosting is there any way to run both servers at a time? -
TypeError: einsatznummer_generator() missing 1 required positional argument: 'self'
I have tried to add a kind of custom id to my Django model, which is built according to the date of a model field. This should be built according to the format: [year][number]. (e.g. 2021001, 2021002, 2021003..., 2022001) For this purpose, I have designed the following model, which returns the error: TypeError: insert_number_generator() missing 1 required positional argument: 'self'. Because of einsatznummer_generator() is not a class, I don't have to initialise it. Can someone please explain the error in my Custom ID? my models.py: from django.db import models from django.contrib.auth.models import User from django.utils import timezone from django.db.models.fields import CharField, NullBooleanField import datetime class EinsatzPublic(models.Model): STATUS = ( (0,"Entwurf"), (1,"Öffentlich"), (2,"Archiv"), (3,"Papierkorb"), ) author = models.ForeignKey('auth.User', on_delete=models.CASCADE, editable=False, verbose_name="Autor") created = models.DateTimeField(default=timezone.now, editable=False, verbose_name="Erstellt") updated = models.DateTimeField(auto_now= True, editable=False, verbose_name="Aktualisiert") status = models.IntegerField(choices=STATUS, default=0, verbose_name="Status") einsatz_start = models.DateTimeField(verbose_name="Einsatzbeginn") einsatz_end = models.DateTimeField(verbose_name="Einsatzende") #! Custom ID: def einsatznummer_generator(self): year_einsatz = self.einsatz_start.strftime('%Y') last_number = EinsatzPublic.objects.filter(einsatznummer__isnull=False).latest('einsatznummer') if last_number == None: last_number = 000 elif last_number[:-3] != year_einsatz: last_number = 000 einsatznummer_gen = year_einsatz + (last_number + 1) return einsatznummer_gen einsatznummer = models.IntegerField(default=einsatznummer_generator() ,verbose_name="Einsatznummer", editable=False) class Meta: ordering = ['-created'] verbose_name = "Einsatz" verbose_name_plural = "Einsätze" -
need some help to explain code about training image classification with svm in python
Im studying computer vision with OpenCv now, and i got the code from github about face attendance management and im having difficult to understand the training image function, here is the code def train(request): if request.user.username!='admin': return redirect('not-authorised') training_dir='face_recognition_data/training_dataset' count=0 for person_name in os.listdir(training_dir): curr_directory=os.path.join(training_dir,person_name) if not os.path.isdir(curr_directory): continue for imagefile in image_files_in_folder(curr_directory): count+=1 X=[] y=[] i=0 for person_name in os.listdir(training_dir): print(str(person_name)) curr_directory=os.path.join(training_dir,person_name) if not os.path.isdir(curr_directory): continue for imagefile in image_files_in_folder(curr_directory): print(str(imagefile)) image=cv2.imread(imagefile) try: X.append((face_recognition.face_encodings(image)[0]).tolist()) y.append(person_name) i+=1 except: print("removed") os.remove(imagefile) targets=np.array(y) encoder = LabelEncoder() encoder.fit(y) y=encoder.transform(y) X1=np.array(X) print("shape: "+ str(X1.shape)) np.save('face_recognition_data/classes.npy', encoder.classes_) svc = SVC(kernel='linear',probability=True) svc.fit(X1,y) svc_save_path="face_recognition_data/svc.sav" with open(svc_save_path, 'wb') as f: pickle.dump(svc,f) vizualize_Data(X1,targets) messages.success(request, f'Training Complete.') return render(request,"recognition/train.html") please i hope somebody could give me the review about that code -
How to delete a record permanently from Django?
Models:- I have a staff model class Staffs(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE) address = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() Then I have a subject model class Subjects(models.Model): id =models.AutoField(primary_key=True) subject_name = models.CharField(max_length=255) course_id = models.ForeignKey(Courses, on_delete=models.CASCADE, default=1) #need to give defauult course staff_id = models.ForeignKey(CustomUser, on_delete=models.CASCADE) #created_at = models.DateTimeField(auto_now_add=True) #updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() Views:- def add_subject(request): courses = Courses.objects.all() staffs = CustomUser.objects.filter(user_type='2') context = { "courses": courses, "staffs": staffs } return render(request, 'hod_template/add_subject_template.html', context) def add_subject_save(request): if request.method != "POST": messages.error(request, "Method Not Allowed!") return redirect('add_subject') else: subject_name = request.POST.get('subject') course_id = request.POST.get('course') course = Courses.objects.get(id=course_id) staff_id = request.POST.get('staff') staff = CustomUser.objects.get(id=staff_id) try: subject = Subjects(subject_name=subject_name, course_id=course, staff_id=staff) subject.save() messages.success(request, "Subject Added Successfully!") return redirect('add_subject') except: messages.error(request, "Failed to Add Subject!") return redirect('add_subject') def manage_subject(request): subjects = Subjects.objects.all() context = { "subjects": subjects } return render(request, 'hod_template/manage_subject_template.html', context) def edit_subject(request, subject_id): subject = Subjects.objects.get(id=subject_id) courses = Courses.objects.all() staffs = CustomUser.objects.filter(user_type='2') context = { "subject": subject, "courses": courses, "staffs": staffs, "id": subject_id } return render(request, 'hod_template/edit_subject_template.html', context) def edit_subject_save(request): if request.method != "POST": HttpResponse("Invalid Method.") else: subject_id = request.POST.get('subject_id') subject_name = request.POST.get('subject') course_id = request.POST.get('course') staff_id = request.POST.get('staff') try: … -
How to integrate social login from reactjs with Django using django-allauth and django-restauth
Using Django template-based view, I am able to integrate django-allauth and perform Social Login using google and Facebook accounts. Now I want to do the same using reactjs using REST or Graphql query. Any example, pointers to some reference will help. -
Get Client IP address and other details with Django
I am building a webbase django app to get to update my organization asset register workstations output on pythonanywhere.com output on my localserver I need the it to get anyone's system details not mine. Please help -
How to Paginate a type as you search with Ajax in a Django app
I'm implementing a type as you search with ajax in a Django app with pagination. I want results to refresh as the user types their search term in the database instead of a form with a submit button. I'm using Django's inbuilt pagination to paginate the data and display it in the template. Right now: HTTP GET parameters are handled in Django views and make our view capture the user’s query. The Django view handle Ajax requests and respond to them properly with a JSON response containing the new (template) results. JavaScript and jQuery send an Ajax request to our view once the user starts typing in the HTML search box. This request will include the term so the server can return relevant results. Once our view returns the JSON response, our JS code will use it to change the information presented to the user without a page-refresh. Problem: At the moment, When I receive my searched results and go to the second page, I receive results unrelated to the search query which I believe is lost. E.g search 'John', I have a list of objects(artists name) with 'John' as its name. When I press the next page because there … -
cant connect to stripe webhook with Heroku
iam currently deployed my website on Heroku but after the user pay for the order Stripe Webhook dosent work at all although it worked before in (Development) so how can i work with Stripe in production with Heroku this is stripe views.py def create_checkout_session(request): YOUR_DOMAIN="**********" order=Order.objects.get(user=request.user,ordered=False) for i in order.items.all(): items=i.quantity checkout_session = stripe.checkout.Session.create( payment_method_types=['card'], locale = "auto", shipping_address_collection={ 'allowed_countries': ['EG'], }, # shipping_rates="null", line_items=[ { 'price_data': { 'currency': 'EGP', 'unit_amount': int(order.get_total_price()*100), #cents 'product_data': { 'name':str(order.user), 'images': ['https://cdn.business2community.com/wp-content/uploads/2020/05/Ecommerce-marketing-trends.jpeg'], }, }, 'quantity': 1, }, ], metadata={ "order_id":order.id, "order":order, }, mode='payment', success_url=YOUR_DOMAIN + 'success/', cancel_url=YOUR_DOMAIN + 'cancel/', ) return JsonResponse({'id': checkout_session.id}) and this is my webhook views.py @csrf_exempt #this is to make post request is no longer need a csrf_toekn on this view def my_webhook_view(request): payload = request.body print(payload) sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None try: event = stripe.Webhook.construct_event( payload, sig_header,settings.STRIPE_WEBHOOK_SECRET ) except ValueError as e: # Invalid payload return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: # Invalid signature return HttpResponse(status=400) # Handle the checkout.session.completed event if event['type'] == 'checkout.session.completed': session = event['data']['object'] order=session["metadata"]["order"] my_order=Order.objects.get(id=order) my_order.ordered=True for i in my_order.items.all(): i.ordered=True i.save() my_order.save() final=final_order.objects.get(order=my_order) final.customer_email=session["customer_details"]["email"] final.payment_intent=session["payment_intent"] final.city=session["shipping"]["address"]["city"] final.country=session["shipping"]["address"]["country"] final.line1=session["shipping"]["address"]["line1"] final.line2=session["shipping"]["address"]["line2"] final.postal_code=session["shipping"]["address"]["postal_code"] final.ordered=True final.save() send_mail( subject="completed payment", message=f"your payment completed successfully using {final.money}", from_email=settings.EMAIL_HOST_USER, … -
Multiple Django/Nginx projects with the same user authentication
I have set up two Django projects using Gunicorn and Nginx. I have successfully managed to set up my configuration and everything works fine, but when navigating through different projects, I get logged out from the other project. So let's say I have the first project at localhost/ and the second one at localhost/the-other-project. If I log in to localhost/the-other-project and then go back to localhost/, I get logged out from the project that I logged in to before. The same problem occurs vice versa. Any tip on what I need to do to keep the user logged in when switching locations on Nginx? -
How do I properly strcuture and use my models and tables in Django?
I was facing error in Django which was difficult to understand and solve. Error was because of importing conflicts from the different apps. I had 3 apps camp reservation payment When I imported model from camp to reservation and from reservation to camp I encountered error ImportError cannot import 'Reservation' from reservation.models So in order to solve the error I had user double quotes in order to connect tables to each other My question is how do I structure database tables in Django? Should each app contain its tables or should I create one sepeate app for example 'main' and keep all my models there? -
Overwrite image located outside django MEDIA_ROOT
My models.imageField uploads images to a directory outside of the django directory path. In storages.py I have a function 'upload_to' that sets the directory and filename. It all works perfectly except that I cannot overwrite an existing file with the same name, django simply appends some random text to the file name. My question is: How can I overwrite the remote file? What I have tried: I have played around with the script suggested here: https://www.itachay.com/2020/04/override-replace-uploaded-file-in-django.html Which would work if I was using MEDIA_ROOT, but with my remote file I only ever get the django "SuspiciousFileOperation" warning. Here is my 'working' code albeit that it won't overwrite any existing file of the same name. models.py from .storages import upload_to, remote_storage class Newsletter(models.Model): image_1 = models.ImageField(upload_to=upload_to, storage=remote_storage) storages.py from django.core.files.storage import FileSystemStorage def upload_to(instance, filename): dir_name = 'volume-'+str(instance.pk) filename = 'image_1'+filename[-4:] return '%s/%s' % (dir_name, filename) remote_storage = FileSystemStorage( location='/Users/some_dir/Documents/dev/mediatest/', base_url='/Users/some_dir/Documents/dev/mediatest/' ) -
JSON Dump a string surrounded by single quotes and containing escaped single quotes
I'm going mad! I'm working on a Django web app and I have a problem. I have a page where i list all the results in a MySQL table, and it works fine. {% for row in db_list %} <tr> <th scope="row">{{ row.description }}</th> <td> <button type="submit" name="instance" value="{{ row }}" class="btn btn-primary" title="OPEN TABLE" id="test"><i class="fas fa-list-ul"></i></button> </td> </tr> {% endfor %} Depending on the selection, I have to show the relations of the chosen table, and it works fine with a workaround, but it's not generalistic. What I'm doing is, as you see, transferring back a single row of the json. The db_list is: { "db_list": [ { "description": "description", "table_name": "table_name", "database_name": "database_name" }, { "description": "description", "table_name": "table_name", "database_name": "database_name" }, { "description": "description", "table_name": "table_name", "database_name": "database_name" } ] } I would expect to transfer a json like this: { "description": "description", "table_name": "table_name", "database_name": "database_name" } In this case, I would treat it with the json.dumps() and retrieving the fields I need to execute the query with a simple command and everything would be fine. But I get an escaped string, surrounded by two quotes.. '{ \'description\': \'description\', \'table_name\': \'table_name\', \'database_name\': \'database_name\' }' This … -
conditionally display columns in Django admin based on filtered queryset
I want to hide some columns in the django admin when all the values in that column are null. I have tried using get_list_display but the queryset returned is the one before being filtered, therefore it's no use. def get_list_display(self, request): result = super().get_list_display(request) # remove some columns when there's no data, to save space if not any(d.node_type for d in super().get_queryset(request)): result = (r for r in result if r not in {'node_type', 'mesh_layer'}) return result It's just occured to me that the value of list_display is probably affecting the final query itself, is there some way to filter the columns shown after the query but before displaying the final result? -
Django Record Locking and Atomic Transactions
I am trying to implement some critical updates in a project that I'm doing. In summary, I need to take information from a work file which does some further processing and then updates it to a final file. This information comes from different sources so it is best to do it on the middle file which then writes it to the final file. My problem is that some of the detail lines data is getting lost among the way. I have duplicated this problem in the below files to eliminate any crud. Simply run the functions in a manage.py shell. This shows up both in Mariadb as well as Postgresql. Is there a better way to achiever this instead of a workaround? The models.py: import random from decimal import Decimal from django.db import models, transaction class Head(models.Model): name = models.CharField(max_length=20, default="") h1_text = models.CharField(max_length=20, default="") def update(self): tmp1 = Tmp1Head() tmp1.name = self.h1_text tmp1.save() for line in self.head_lines.all(): tl1 = Tmp1Line() tl1.head = tmp1 tl1.data_text = line.data_text tl1.t1_data = line.t1_data tl1.t2_data = Decimal(random.random()) tl1.save() with transaction.atomic(): transaction.on_commit(tmp1.update) tmp1.delete() # All fine - remove this work transaction. return True class Line(models.Model): head = models.ForeignKey(Head, on_delete=models.CASCADE, related_name='head_lines') data_text = models.CharField(max_length=20, default="") t1_data … -
Poll is adding multiple votes
I am building a PollApp and I am stuck on a Problem. What i am trying to do :- I am trying to vote only on One choice at a time and if user want to change the voting choice then user can also change the choice. BUT at this time, When user is selecting first choice then it is adding vote again and again and if user is selecting second option then both are adding ( first choice and second choice ). BUT i am trying to add only one choice at a time. views.py def poll_vote(request, poll_id): poll = get_object_or_404(Poll, pk=poll_id) choice_id = request.POST.get('choice') if choice_id: choice = Choice.objects.get(id=choice_id) vote = Vote(user=request.user, poll=poll, choice=choice) vote.save() print(vote) return render(request, 'polls/poll_result.html', {'poll': poll}) else: messages.error( request, "No choice selected") return redirect("polls:polls_detail_view", poll_id) return render(request, 'polls/poll_result.html', {'poll': poll}) I also tried this in poll_vote view if not poll.user_can_vote(request.user): messages.error(request, "You already voted this poll") return redirect("polls:polls_detail_view",poll_id=poll_id) This is working fine like :- When user is voting first choice then it is preventing user from selecting second choice BUT i want, user can change another option after vote. models.py class Poll(models.Model): owner = models.ForeignKey(User,null=True,on_delete=models.CASCADE) text = models.TextField() date = models.DateTimeField(default=timezone.now) def user_can_vote(self, … -
How to solve Javascript template not returning correct value issue in Django,?
I created some values with various operations in my views. Since I am using USE_THOUSAND_SEPARATOR = True in the project, I am going through some operations (otherwise the charts don't work), when I print the final value in the terminal, the value appears correctly. But in the template, it does not take the full value of the integer in javascript, it shows incomplete. For example, in views terminal: print(t1credit) --> 2241825 (Correct) in template: window.alert( ({{ t1credit }}) ) --> 2 (not correct) How can I solve it? views.py top_1_country = Customer.objects.values( 'country__country_name' ).annotate(Count('country'), Sum('credit_limit')).order_by('-country__count')[:1] t1country = "" t1count = 0 t1credit = 0 counter = 0 for top in top_1_country: for q,w in top.items(): if counter == 0: t1country = w elif counter == 1: t1count = w else: t1credit = w counter += 1 sep = '.' t1credit = str(t1credit) t1credit = t1credit.split(sep, 1)[0] t1credit = t1credit.replace(',', '') t1credit = int(t1credit) -
How to check if the form is edit/view/create form in a template for Django admin
I want to customize the view only template in Django admin and want to add custom CSS class if the user opens the view only form (for example class="test_class"). I tried this to change the class for edit form so I can use the default one for add and change templates: Can I tell if a form is an 'edit' form in a template? but it doesn't work. I don't see my custom class when I inspect the form. I want to know if there is a more "cleaner" solutions than this: How to add css class to Django admin form For example (this is a pure guess) something like this in change_form.html: <form {% if form.is_change_form %} class="test_class" {% endif %}