Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not able to inspect django migrations from test but working from django command
I want to be able to inspect Django migrations within a test (so I can check basic sanity before running more expansive tests). For doing that I was able to do the following in a django command: from django.core.management.base import BaseCommand from django.db.migrations.loader import MigrationLoader class Command(BaseCommand): help = "Check migrations" def handle(self, *args, **options): self.migration_loader = MigrationLoader(None) self.migration_loader.build_graph() for root_node in self.migration_loader.graph.root_nodes(): print(app_name, root_node[0]) But when I translate that into a test (using pytest): from django.db.migrations.loader import MigrationLoader def test_multiple_leaf_nodes_in_migration_graph(): migration_loader = MigrationLoader(None) migration_loader.build_graph() for root_node in migration_loader.graph.root_nodes(): print(app_name, root_node[0]) Then the graph (root nodes) returns an empty list. Is there anything I need to do so I can "see" migrations within the test ? -
Django - Queryset results not displaying in template
I am learning Django and building an inventory app for a laboratory. I already have data in all my models, and now I want to search the database based on some criteria and display the results in a table. First I ask the user to input the search terms (that part works), then I query the db (that also works) but when it's time to display results all I get is an empty template. No error messages. These are my views: def choose_filter_primers(request): # this works fine if request.method == "GET": radiobtn_form = PrimerRadiobtn(request.GET) if radiobtn_form.is_valid(): # get value from user input and store it in request.session dict request.session['filter_by'] = radiobtn_form.cleaned_data['CHOOSE_FIELD'] # go to the next step in the search form return render(request, 'lab_inventory/filter_primers.html') else: radiobtn_form = PrimerRadiobtn() return render(request, 'lab_inventory/choose_filter_primers.html', {'radiobtn_form': radiobtn_form}) def filter_primers(request): # this works fine # get filter field from views.choose_filter_primers filter_by = request.session.get('filter_by') if request.method == "POST": form = FilterPrimerForm(request.POST)# or None) if form.is_valid(): # get value from user input and store it in request.session dict request.session['contains'] = form.cleaned_data.get("contains") # go to the next step in the search form return render(request, 'lab_inventory/search_results_primers.html') else: return render(request, 'lab_inventory/choose_filter_primers.html') else: form = FilterPrimerForm(request.POST) context = {'form': form} return … -
how can i retrieve data from django database in a json file in my local machine
I have created a school management website for a school nearby my house and I used django as backend for my website. I have the details of a student in my database.. I want all the data stored in django database to show me in a json file in my local machine models.py from django.db import models from django.contrib.auth.models import User class Student(models.Model): id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=1000) last_name = models.CharField(max_length=1000) gender = models.CharField(max_length=225) class_of_joining = models.CharField(max_length=225) adhar_number = models.CharField(max_length=1000) current_address = models.TextField(max_length=1000) permanent_address = models.TextField(max_length=1000) blood_group = models.CharField(max_length=225) -
What is the code for representing suggestions list on the webpage in Django framework
enter image description here How to represent this suggestion list on webpage using django framework? -
Docker container connect problem on browser with p option
First of all, please understand that I can't speak English. I tried many times for port forwarding. But, return message is connection refused. For example, 1. Run my container. 2. Check installed Django 3. Edit ALLOWED_HOSTS 4. Django run server 5. Connection test in container (connected with exec from other terminal 6. Test local browser, but failed if using official image is working (Ubuntu:20.04). but using my image is not working (my image is run Ubuntu:20.04 and committed). T^T My docker image is exists in hub.docker.com docker pull redukyo/ubuntu:qf_user Please help me! -
Django __init__() got an unexpected keyword argument 'user'
Im trying to build a password reset system using the default django libraries. The problem is after trying to enter the site which is for changing it (PasswordChangeConfirm) this error trace appears. Internal Server Error: /reset/confirm/MQ/atg5tq-aa6bcab1c34d1228cdd1970aaaa45252/ Traceback (most recent call last): File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\decorators\debug.py", line 89, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\views.py", line 284, in dispatch return self.render_to_response(self.get_context_data()) File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\views.py", line 308, in get_context_data context = super().get_context_data(**kwargs) File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\views.py", line 200, in get_context_data context = super().get_context_data(**kwargs) File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\edit.py", line 66, in get_context_data kwargs['form'] = self.get_form() File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\edit.py", line 33, in get_form return form_class(**self.get_form_kwargs()) TypeError: __init__() got an unexpected keyword argument 'user' my code: views.py class password_reset_view(PasswordResetConfirmView): form_class = CaptchaPasswordResetForm success_url = reverse_lazy('home:login') urls.py urls.py from StartSite.views import password_reset_view from StartSite.forms import NewPasswordResetForm from StartSite.forms import CaptchaPasswordResetForm from django.contrib import admin from django.urls import path, include from django.urls.base import reverse_lazy from … -
How to get Django queryset in Ajax conform data structure?
I have a view that transforms a queryset into a list which is then returned as JSON for further use of Ajax on client-side. However, since I need multiple fields (namely poller_text and poller_id) of each object Ajax requires the following structure: [ { "value": "poller_text", "label": "poller_text", "url": "poller_id" }, { "value": "poller_text", "label": "poller_text", "url": "poller_id" }, ] Right now this is what I get using the view below: ["poller_text", "poller_id", "poller_text", "poller_id"] # View def autocomplete(request): if 'term' in request.GET: qs = Poller.objects.filter(poller_text__icontains=request.GET.get('term')) pollers = list() for poller in qs: pollers.append(poller.poller_text) pollers.append(poller.poller_id) return JsonResponse(pollers, safe=False) else: pass I think the append loop is badly designed, but how to get the required structure? -
How to avoid users creating new Websockets/Rooms using Django Channels?
I'm basically following this tutorial: https://channels.readthedocs.io/en/stable/tutorial/part_3.html In this simple example, everyone can create and join different rooms. I want to make an webapp where there are existing rooms defined, so I don't want users going around creating random websockets. What would be the best way to achieve this safely? Does simply doing the logic in yours views work? That is, only return a render if it matches a room (url pattern) that's allowed. Is this good enough, or can people bypass this? Could someone for example tamper with the javascript code and create websockets anyway? If I look at the code in front end: # const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/' ); And backend: # def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() It looks to me like people can just temper with the code and make groups on the server unintended? -
Merging querysets and displaying them in template
I am building a Blog App and I am trying to merge two querysets and show them in template at once and order_by('-date') But it not showing both the querysets , it is showing some strange results like user_1 - title - ALL_COMMENTSALL_COMMENTSALL_COMMENTS models.py class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30) def __str__(self): return f"{self.user} - {self.title}" class Likes(models.Model): liker = models.ForeignKey(User, on_delete=models.CASCADE) post_of = models.ForeignKey(BlogPost, on_delete=models.CASCADE) views.py def page(request,blogpost_id): post = get_object_or_404(BlogPost, id=blogpost_id) likes = post.likes_set.all() ALL_RESULTS = [] for q1 in likes: ALL_RESULTS .append(q1) for q2 in anotherQueryset: ALL_RESULTS .append(q2) context = {'ALL_RESULTS':ALL_RESULTS} return render(request, 'page.html', context} page.html {% for set in ALL_RESULTS %} {{set}} {% endfor %} It is showing :- user_1 - first_post - ALL_COMMENTSALL_COMMENTSALL_COMMENTS What have i tried so far ? :- I have tried using | operator like :- all_results = FIRST_LIST | SECOND_LIST But then i read that it will only work in same model, But i am accessing from two different models. Than i tried chain method like :- from itertools import chain result_list = list(chain(FIRST_LIST, SECOND_LIST)) Any help would be much Appreciated. Thank You -
Handling day objects and date in string format
Please bear with me as I try my best to explain the problem. As the title states I am struggling to find a solution for this problem I have whereby days (Mon, Tue, Wed, etc) are objects, and I have dates (DD/MM/YY) in string format. What I would like to do is for a specific date to be able to identify the corresponding day object. For example, say if I have a chosen date 25/09/21 - which is a Saturday, and I have an array of day objects Mon (id 001) Tue (id 002) Wed (id 003) Thu (id 004) Fri (id 005) Sat (id 006) Sun (id 007) How can I get it so that the date is able to identify the correct day? To add to the problem, say again I have a chosen date 25/09/21 - Saturday, and I have an array of Saturday-only day objects Sat (id 010) Sat (id 017) Sat (id 003) What would I need to do in order for the date to be able to identify the 'correct' Sat object? Thanks in advance. -
how can i download the exact uploaded file in django..?
I was writing a code to download my file using a link which I have uploaded through the model in django. i.e in my model.py class uploadFile(models.Model): id=models.CharField("Book id ",max_length=200,null=True,default="") name=models.CharField("Book name",max_length=200,null=True,default="") file=models.FileField(upload_to="media/ebooks") and in my view.py I have 2 functions def getdata(request): books=uploadFile.objects.all() n=len(QPapers) print("hello",QPapers) params={'QPapr':QPapers,'total_items':n} return render(request,'index.html',params) def getdata2(request,nameparam): books=uploadFile.objects.all().filter(name=nameparam) n=len(QPapers) print("hello",QPapers) params={'QPapr':QPapers,'total_items':n} return render(request,'index.html',params) and in index.html <a href="{% 'getdata' %}" download>download1</a> for this urls.py is path('getdata',views.pdfNotes,name='pdfNotes'), here the file downloads correctly using above code but when i am using the below code and calls to 2nd function with the name of book then instead of downloading file i have uploaded it downloads the index.html page. <a href="{% 'getdata2' 'book1' %}" download>download2</a> for this urls.py is path('getdata2/<str:name>/',views.pdfNotes,name='pdfNotes'), is it because of filter i am using ? or problem is somewhere else ? i want to be download the specific file also that's why i am using the filter here... please share if any solution u have. -
How to pass instance while save serializer data using Django rest framework?
i want to save two serializers data using single API. i don't understand how can i pass post instance model with file serirializer. i want to pass the post_ser instance data with file_ser which is created at same time. models.py class PostFileModel(models.Model): post = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='post') file = models.FileField(upload_to=file_path) views.py class PostFileSerializer(APIView): parser_class = (MultiPartParser,) def post(self, request, *args, **kwargs): post_ser = ArticleSerializer(data=request.data) file_ser = FileSerializer(data=request.data) if post_ser.is_valid() and file_ser.is_valid(): post = post_ser.save(author=self.request.user) file_ser.save(post=post) # post instance getting empty error return Response(post_ser.data, status=status.HTTP_201_CREATED) else: return Response(post_ser.errors, status=status.HTTP_400_BAD_REQUEST) -
Djando Form's input fields are only shown after submitting invalid form
I am working on an educational Auctions app which should allow Users to place a bid and add comments to an existing auction listing. I want to implement comments as a CommentForm and include this form's snippet comment_add.html into the view_listing.html template, which in turn extends base layout.html. But the view_listing.html initially doesn't show input field from comment_add.html. The "textarea" input field shows only after pressing "submit button" as it is a required field. Expected result: screenshot of the "Comment" area of the page Actual result: screenshot of the "Comment" area of the page Result after pressing "Commit": screenshot of the "Comment" area of the page Of course implementing comment input field as an <input> in comment_add.html works. I was guessing the problem has something to do with the same context being passed to view_listing.html from other views (context variable name is the same for all views - "listing"). But so far I wasn't able to figure out the decision. views.py def comment_add(request, listing_id): listing = Listing.objects.get(pk=listing_id) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): text = form.cleaned_data["text"] author = User.objects.get(pk=request.user.id) comment = Comment(text=text, author=author) comment.save() context = {"form": form, "listing": listing} return HttpResponseRedirect(reverse("auctions:listing", args=(listing.id,))) else: context = {"form": … -
Deploying Python, takes forever to build wheel for cryptography
I'm running a Django Python project in Heroku, and to support the Python cryptography package, my dockerfile contains instructions to first install the non-Python dependencies for that package: run apk add openssl-dev cargo And then my build log shows that deployment builds various wheels. The cryptography wheel takes several minutes to build: Building wheel for cryptography (PEP 517): started Building wheel for cryptography (PEP 517): still running... Building wheel for cryptography (PEP 517): still running... Building wheel for cryptography (PEP 517): finished with status 'done' Created wheel for cryptography: filename=cryptography-3.4.7-cp38-cp38-linux_x86_64.whl size=534047 sha256=8c3212278fa23bad7ecfbc54d036e8d35ba9308479d87e8ec39697aed26095dc Is there any kind of precompiled wheel or buildpack or similar that I can use to more speed up my deployments? -
Which URL link pattern should I use in Django
Please help me take a look at this question. I just find out there are some ways to create a link in Django: 1. <a href='/blog/{{ object.id }}'>{{ object.title }}</a> 2. <a href='{% url "blog:detail" id=object.id %}'>{{ object.title }}</a> 3. <a href='{{ object.get_absolute_url }}'>{{ object.title }}</a> When should I use these pattern? Are there any special for earch one? Thank you so much. -
logging users actions in django
seeking to log what users do in mi django app, i try to log when a django session is opened and also when a view is executed. To do that i found a solution but i wonder if it is correct and also if there are not other better ways or tools to do that. Could somebody tell me ? Thanks a lot. the log file is written like this : # in case django session open datetime / ----New Session ------ / session_id # in case view execution datetime / -session_id- / view_name I have for this a function : # logs visited page and session id and session opening def f_lou_log(request, page="???"): if not request.session.session_key: request.session.create() logger.warning(str(datetime.datetime.now()) + " -------------------- New session --- #" + request.session.session_key) logger.warning(str(datetime.datetime.now()) + " - #" + request.session.session_key + " - " + page) return 1 and at the beginning of every view i call the function like that : def some_view(request): # log record v_wait = f_lou_log(request,"some_view") # (...) here is the view code and for instance my log file looks like that : 2021-09-24 17:24:27.110718 -------------------- New session --- #x0u30n1th4b3z0otv311883ikf0d8y34 2021-09-24 17:24:27.110718 - #x0u30n1th4b3z0otv311883ikf0d8y34 - home 2021-09-24 17:24:31.373336 -------------------- New session … -
django rest framweork: combine ValidationError from multiple validation
Let's say I have the following serializers: class AnswerSerializer(ModelSerializer): answer_text=CharField() def validate_answer_text(self, value): ... return value def validate(self, value): ... return value class QuestionSerializer(ModelSerializer): question_text=CharField() answer=AnswerSerializer(many=True, read_only=False) def validate_question_text(self, value): ... return value def validate(self, value): ... return value If validate_answer_text or validate in AnswerSerializer or validate_question_text in QuestionSerializer raise a ValidationError, the validate of QuestionSerializer won't be runned. Thus, I cannot explain all the problem of the POST datas. Is there a way to run the validate function of a serializer even if one of it's field validator or children serializer validation failed and then combine all the errors ? I have tried the following but did not succeed make it work properly. It does run both validate function and other validators but you cannot nest AllErrorSerializer and more importantely, it does not work when you do not have error: you cannt save instance because you have inspect serializer.data. -
Why does django cart template_tags bring the error message object has no attribute 'is_authenticated'
register = template.Library() @register.filter def cart_item_count(user): if user.is_authenticated: qs = Order.objects.filter(user=user, ordered=False) if qs.exists(): return qs[0].item.count() return 0 -
Django query is not reaching to the the page
I want to add a contact html page in my existing project. I put the html page in template where homepage is already residing. Now I have added a url for contact in project level directory which directing the query to app level url. This app level has a contact function in views. I have setup app level url as well but contact link isnt responding. In debug its showing a 200 ok status. Could somebody can point out to me what wrong i am doing??? This is project level url file urlpatterns = [ path('admin/', admin.site.urls), path('', include('articles.urls')), path('contact', include('articles.urls')), ] this is app level url file urlpatterns = [ path('', views.articles, name='articles'), path('', views.contact, name='contact'), ] this is view function in which one function is returning article page but other one not responding def articles(request): return render(request, 'articles/home.html') def contact(request): return render(request, 'articles/contact.html') -
Field 'id' expected a number but got '' error on creating table entry
I'm working on an ebay style auction website. I've created my models and have a form that creates a new listing. When the POST request goes out, the listing gets created when I try to add the listing to the bid, I get the error Field 'id' expected a number but got '' I'm fairly new to Django so if you need anything that I haven't included, please let me know! models.py class Listing(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=500) url = models.URLField() author = models.ForeignKey('User', on_delete=models.CASCADE, name='author') category_id = models.ForeignKey('Category', on_delete=models.CASCADE, name='category', default="") def __str__(self): return f'{self.id}: {self.title}' class Bid(models.Model): price = models.DecimalField(decimal_places=2, max_digits=10) bid_count = models.IntegerField() listing = models.ForeignKey('Listing', on_delete=models.CASCADE, name='listing', default="") def __str__(self): return f'{self.slug} ({self.price})' views.py def newListing(request): try: if request.method == "POST": newListingForm = NewListingForm(request.POST) if newListingForm.is_valid(): title = newListingForm.cleaned_data['title'] description = newListingForm.cleaned_data['description'] url = newListingForm.cleaned_data['url'] bid = newListingForm.cleaned_data['bid'] category_name = newListingForm.cleaned_data['category'] category = Category.objects.get(title=category_name) category_id = category.id current_user = request.user l = Listing(title=title, description=description, url=url, author=current_user, category_id=category_id) l.save() print(l.id) b = Bid(price=bid, bid_count=0) b.listing.add(l.id) b.save() return HttpResponseRedirect(reverse("index")) else: newListingForm = NewListingForm() return render(request, "auctions/newListing.html", { 'form': newListingForm }) except Exception as exc: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print(exc_type, exc_obj, fname, exc_tb.tb_lineno) … -
django define a json type instead of jsonb type on models
I am using the JSONField for my Django model for JSON type but in the background, it makes my attributes column type JSONB which I don't want to do here because it breaks my exact order of JSON'S internal field that I pushed from my frontend app. You can see the order of fields is not my exact value. To store it as it is, I need to use JSON instead of jsonb. So my question is how to do that? What I pushed: { "type": "array", "title": "action_right", "additionalProperties": true, "items": { "type": "object", "required": [ "label", "url" ], "properties": { "label": { "type": "string", "custom_type": "string", "title": "label", "default": "" }, "url": { "type": "string", "custom_type": "string", "title": "url", "default": "" } } } } What is stored: { "type": "array", "items": { "type": "object", "required": [ "label", "url" ], "properties": { "url": { "type": "string", "title": "url", "default": "", "custom_type": "string" }, "label": { "type": "string", "title": "label", "default": "", "custom_type": "string" } } }, "title": "action_right", "additionalProperties": true } Code snippets: class Component(models.Model): name = models.CharField(max_length=200, unique=True) attributes = models.JSONField(default=dict, help_text='Component attributes in JSONSchema') Notes: PostgreSQL has two native JSON based data types: json and jsonb. … -
Ye error aa rha -------- Django.db.utlis.IntegrityError: UNIQUE constraint failed : accounts_user. username
Integrity error in my code in Django . I have created a custom user model -
Submit dynamic dual list box with django
I have a dual dynamic list box in a django form, I'm using jquery..it is an adaptation of this plugin: https://www.jqueryscript.net/form/Dual-List-Box-Multi-Selection.html It works when I try to pass an element from the left box to the other. When I submit the form If I print the form variable, for the second box I receive an error: <tr><th><label for="id_selected_stations">Selected stations:</label></th><td><ul class="errorlist"><li>Scegli un&#x27;opzione valida. 22 non è tra quelle disponibili. </li></ul><select name="selected_stations" required id="id_selected_stations" multiple> Is it wrong the box type? When I submit the form I need to acquire only the data of the right box (users selected options). This is my code: forms.py from django import forms from station.models import Station station_all=Station.objects.all() class VdlForm(forms.Form): vdl_name = forms.CharField(label='nome virtual data logger', max_length=20, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'nome vdl'})) stations = forms.ModelMultipleChoiceField(queryset=station_all) selected_stations = forms.ModelMultipleChoiceField(queryset=Station.objects.none()) views.py from django.http import HttpResponseRedirect from django.shortcuts import render, redirect from .forms import VdlForm def new_vdl(request): template_name = 'vdl.html' heading_message = 'Add a new vdl' if request.method == 'POST': form = VdlForm(request.POST or None) if form.is_valid(): vdl_name = form.cleaned_data.get("vdl_name") stations = form.cleaned_data.get("stations") selected_stations = form.cleaned_data.get("selected_stations") return HttpResponseRedirect('new_vdl') else: form = VdlForm() return render(request, template_name, {'form': form, 'heading': heading_message, }) vdl.html {% extends 'base.html' %} {% block content %} … -
Persian text in url djngo
I have some links that include Persian texts, such as: http://sample.com/fields/طب%20نظامی and in the view function i want to access to Persian part, so: request.path_info key = re.findall('/fields/(.+)', url)[0] and i get the error: IndexError at /fields/ list index out of range Actually, the problem is with the index zero because it can not see any thing there! It should be noted that it is a Django project on IIS Server and I have successfully tested it with other servers and the local server. I think it has some thing related to IIS. Moreover i have tried to slugify the url without success. I can encode urls successfully, but i think it is not the actual answer to this question. -
FF92.0 on linux introduces caching issues with django 3.2 inline forms
I've noticed a strange behavior with FF 92.0 (Manjaro Linux, but likely all linux I guess) when using inline forms. Setup: Django inline forms A way to add inlines ajax. I'm using the django forms empty_form Some arbitray # of inline saved on the server for that object (for example, say 3) Load the form, add say 2 inlines using javascript. TOTAL_FORMS now shows value=5 Do NOT submit the form, but F5 for a refresh instead After reload, the inlines shown in the table will mirror that of the server However the TOTAL_FORMS from the management_form will show value=5, instead of the 3 it should. page.js: function insert_inlinedets_form () { let form_idx = $('#id_details-TOTAL_FORMS').val(); console.log("inserting new form " + form_idx); let newrow = $('<tr></tr>').appendTo($('#details_form')); newrow.append($('#empty_form_inlinedets').html().replace(/__prefix__/g, form_idx)); $('#id_details-TOTAL_FORMS').val(parseInt(form_idx)+1); console.log("added row to inlinedets formset"); }; function remove_inlinedets_form () { console.log("remove last form "); let form_idx = $('#id_details-TOTAL_FORMS').val(); if (form_idx>0) { $('#details_form > tr').last().remove(); $('#id_details-TOTAL_FORMS').val(parseInt(form_idx)-1); console.log("removed row from inlinedets"); calc_grand_total(); // existing rows haven't changed but the total might } else { $('#id_details-TOTAL_FORMS').val(); // if no form left, this SHOULD be 0. console.log("No more dets left - nothing done."); } }; html - empty form: <div style="display:none"> <table> <thead></thead> <tbody> <tr id="empty_form_inlinedets"> {% …