Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
date formatting datefield in django
I want to have thew given format "dd/mm/yyyy" overall the application, but momentally I havee "mm/dd/yyyy". Here's the code in models.py period_from = models.DateField(db_column="Period From", blank=True, null=True) How to define it for all the datefields and in which file? -
How do web development frameworks work exactly?
To my (probably flawed) knowledge, the front-end of websites are built with HTML, CSS, and JavaScript but I hear a lot of talk about using frameworks like Django (Python), ASP.NET (C#), Ruby on Rails (Ruby), Spring (Java) etc... How do these frameworks function? At first I thought they were back-end frameworks but apparently Django can be used to help with HTML formatting and such. I thought these things are only possible with JavaScript? I understand how frameworks like React or Angular can be used because those run on JavaScript but how do these other frameworks and languages work? Do they transpile to JS or something? -
Log User in Celery Task in Django
I have an application where we do need to maintain some kind of audit log which shall display which user changed what data in the db at what time. I implemented a simple solution using signals. I therefore created an app called "actions" where I log all necessary information. To to so I connected three signals (presave, postsave and predelete): apps.py class ActionsConfig(AppConfig): name = 'actions' def ready(self): apps_to_audit = ['app1', 'app2', 'app3'] for app in apps_to_audit: app_models = apps.get_app_config(app).get_models() for model in app_models: pre_save.connect(pre_save_signal, sender=f'{app}.{model.__name__}', dispatch_uid=f'{app}_{model}_pre_save') post_save.connect(post_save_signal, sender=f'{app}.{model.__name__}', dispatch_uid=f'{app}_{model}_post_save') pre_delete.connect(pre_delete_signal, sender=f'{app}.{model.__name__}', dispatch_uid=f'{app}_{model}_pre_delete') then i created a celery function to store the data within the actions-model: tasks.py @shared_task def log_action(action): from actions.models import Action from users.models import CustomUser app_label = action.get('app') model_name = action.get('object') user_pk = action.get('user') action_type = action.get('action_type') updated_fields = action.get('updated_fields') # Get Object Object = apps.get_model(app_label=app_label, model_name=model_name) model_pk = action.get('model_pk') # Get Object instance try: target = Object.objects.get(pk=model_pk) except Object.DoesNotExist: target = None # Get User try: user = CustomUser.objects.get(pk=user_pk) except CustomUser.DoesNotExist: user = None # LOGIC TO DEFINE VERB verb = '' if action_type == 1: verb = f' created new {model_name}' elif action_type == 2: verb = f' updated {model_name}' elif action_type == 3: verb … -
Dynamic template tags in django
I'm building an html page in Django, which has the following structure: {% extends 'main/base_template.html' %} {% load filters %} {% block main_window %} <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4"> <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom"> <h1 class="h2">Stuff</h1> </div> <div class="row mb-3"> <div class="col-12 col-md-6"> {% include 'main/stuff/stuff_A.html' %} </div> <div class="col-12 col-md-6"> {% include 'main/stuff/stuff_B.html' %} </div> </div> <div class="row mb-3"> <div class="col-12 col-md-6"> {% include 'main/stuff/stuff_C.html' %} </div> <div class="col-12 col-md-6"> {% include 'main/stuff/stuff_D.html' %} </div> </div> {% endblock %} And each of the stuff_X html file has the same structure, for example: <div class="row mb-3"> <div class="table-responsive"> <table class="table table-striped table-sm caption-top" style="width:40em"> <caption>Data</caption> <thead> <tr> <th scope="col">Data1</th> <th scope="col">Data2</th> <th scope="col">Data3</th> </tr> </thead> <tbody> <tr> <td id="stuff_a_data1" style="width:5em">{{ stuff_a.data1 }}</td> <td id="stuff_a_data2" style="width:5em">{{ stuff_a.data2 }}</td> <td id="stuff_a_data3" style="width:5em">{{ stuff_a.data2 }}</td> </tr> </tbody> </table> </div> </div> So the only things that actually change are some ids and the name of the data to be retrieved from the django context. Are there any mechanisms that allow me to write generic pages for cases like this? Cause currently I am handling 4 (almost) identical pages, adding snippets of code in each of them when I need … -
How to get user info from json file from django rest framework
I am having this problem. I want to fetch the data from my other file using GET method. but it always says, TypeError: Cannot read properties of undefined (reading 'then') how do I get this response data from any file? the file is given bellow APIService export default class APIService { // get user data static GetUser(userId, token) { fetch(`http://127.0.0.1:8000/pp/users/${userId}/`, { method: "GET", headers: { "Content-Type": "application/json", Authorization: `Token ${token}`, }, }); } static GetUserS(token) { fetch("http://127.0.0.1:8000/pp/users/", { method: "GET", headers: { "Content-Type": "application/json", Authorization: `Token ${token}`, }, }); } } -
How to display tuple items inside template
I want to use items from a tuple I'm currently using in my models.py inside my template. I added this tuple to my views' context but when I try to loop over it nothing shows up. this is my simplified view: def dashboard(request): documents = DocumentInfo.objects.filter(user=request.user) context = {'documents':documents} if request.user.role == 'theory_interviewer': template = loader.get_template('reg/scientific-info-dashboard.html') interviewed = ScientificInfo.objects.filter(is_interviewed=True).all() context['interviewed'] = len(interviewed) context['survey_choices'] = SURVEY_CHOICES return HttpResponse(template.render(request=request, context=context)) and this is my template: {% for x,y in survey_choices %} {{x}}{{y}} {% endfor %} and finally, this is the choice tuple I imported from models.py: SURVEY_CHOICES = ( ('0', 'very bad'), ('1', 'bad'), ('2', 'good'), ('3', 'very good'), ('4', 'nice') ) -
Django: Unable to add post in admin
Right now when I go to admin and want to add post, I get this message: NoReverseMatch at /admin/blog/post/add/ Reverse for 'django_summernote-upload_attachment' not found. 'django_summernote-upload_attachment' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8080/admin/blog/post/add/ Django Version: 3.2.9 Exception Type: NoReverseMatch Exception Value: Reverse for 'django_summernote-upload_attachment' not found. 'django_summernote-upload_attachment' is not a valid view function or pattern name. Exception Location: C:\Download\Development\NowaStrona_Django\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: C:\Download\Development\NowaStrona_Django\Scripts\python.exe Python Version: 3.7.3 Python Path: ['C:\\Download\\Development\\NowaStrona_Django\\mysite\\my_site', 'C:\\Download\\Development\\NowaStrona_Django\\Scripts\\python37.zip', 'C:\\Download\\Development\\NowaStrona_Django\\DLLs', 'C:\\Download\\Development\\NowaStrona_Django\\lib', 'C:\\Download\\Development\\NowaStrona_Django\\Scripts', 'c:\\program files (x86)\\python37-32\\Lib', 'c:\\program files (x86)\\python37-32\\DLLs', 'C:\\Download\\Development\\NowaStrona_Django', 'C:\\Download\\Development\\NowaStrona_Django\\lib\\site-packages'] Server time: Tue, 21 Dec 2021 17:36:13 +0000 Error during template rendering In template C:\Download\Development\NowaStrona_Django\lib\site-packages\django\contrib\admin\templates\admin\includes\fieldset.html, error at line 19 Reverse for 'django_summernote-upload_attachment' not found. 'django_summernote-upload_attachment' is not a valid view function or pattern name. 9 {% for field in line %} 10 <div{% if not line.fields|length_is:'1' %} class="fieldBox{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}"{% elif field.is_checkbox %} class="checkbox-row"{% endif %}> 11 {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %} 12 {% if field.is_checkbox %} 13 {{ field.field }}{{ field.label_tag }} 14 {% else %} 15 {{ field.label_tag }} … -
Django groups, roles and permissions
I have a question: there's employee app in my project and I want employees to have different titles such as sales representative, manager and etc. and my views behave differently depending on employee's title. For now I have model Titles (title_code, title_name) but I feel like it could've been done with Django's builtin modules. So what do I use for building hierarchy? Groups, roles or permissions? -
Does django-ckeditor works with django-modeltranslation
I use django-modeltranslation to translate some text fields into several languagues. This works well. Now I want to implement django-ckeditor and this is working for not translated field as well. Problem is with fields which is translated (this fields are registered in translation.py). Does anybody using these two apps together? Is there something to do to get translated text fields working with ckeditor? -
Django database error while connecting sqllite
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 92, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\loader.py", line 53, in __init__ self.build_graph() File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\loader.py", line 220, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\recorder.py", line 77, in applied_migrations if self.has_table(): File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 33, in inner return func(*args, **kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 259, in cursor return self._cursor() File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\dummy\base.py", line 20, in complain raise ImproperlyConfigured("settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. -
BaseQuerySet became empty after been as filter condition
official_template_ids became empty after been one of filter condition of SopTask official_template_ids = SopTemplate.objects.filter(draft_id=self.id, status=before_status).values_list('id', flat=True) print('official_template_ids', official_template_ids) # >>> official_template_ids <BaseQuerySet [371]> SopTask.objects.filter(template_id__in=official_template_ids, status=before_status).update(**update_kwargs) print('official_template_ids', official_template_ids) # >>> official_template_ids <BaseQuerySet []> -
Django chunked upload on apache2
I am using an django application using the [django chunked-upload][1]. It works locally, but on the apache server, it immediately interrupts. Do I need to add something to apache? Here my config file: <VirtualHost *:80> Alias /static /home/usr/app/static <Directory /home/usr/app/static> Require all granted </Directory> <Directory /home/usr/app/backend> <Files wsgi.py> Require all granted </Files> </Directory> WSGIApplicationGroup %{GLOBAL} WSGIDaemonProcess app python-path=/home/usr/app python -home=/home/usr/app/appEnv WSGIProcessGroup app WSGIScriptAlias / /home/usr/app/backend/wsgi.py WSGIChunkedRequest On ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined SetEnv proxy-sendchunked LogLevel info -
Sidebar's links don't work and the dropdown collapse
I've found a sideber that I'd like to use in my Django project, I was able to edit it to adjust it in the way I want but now I've two problems: The links don't work (for exemple here I'm trying to link to the user profile and nothing happen when the link is clicked) The sidebar dropdown: the dropdown works just fine but when I click one of the link in the sub menu (like Dashboard's "total" the dropdown collapse and it just closed itself) I'm not very good with the css and js stuff. Any help would be very appreciated! Thank you <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="https://unicons.iconscout.com/release/v3.0.6/css/line.css" rel="stylesheet"> <aside class="sidebar position-fixed top-0 left-0 overflow-auto h-100 float-left" id="show-side-navigation1"> <i class="uil-bars close-aside d-md-none d-lg-none" data-close="show-side-navigation1"></i> <div class="sidebar-header d-flex justify-content-center align-items-center px-3 py-4"> <div class="ms-2"> <h5 class="fs-6 mb-0"> <a class="text-decoration-none" href="#">User Name</a> </h5> <p class="mt-1 mb-0">user status</p> </div> </div> <ul class="categories list-unstyled"> <li class="has-dropdown"> <i class="uil-estate fa-fw"></i><a href="#"> Dashboard</a> <ul class="sidebar-dropdown list-unstyled"> <li><a href="#">Total</a></li> <li><a href="#">Partial</a></li> </ul> </li> <li class=""> <i class="uil-user"></i><a href="{% url 'user_profile' %}"> Profile</a> </li> <li class="has-dropdown"> <i class="uil-envelope fa-fw"></i><a href="#"> Inbox</a> <ul class="sidebar-dropdown list-unstyled"> <li><a href="#">Deleted</a></li> </ul> </li> <li class=""> <i class="uil-signout"></i><a href="#"> Logout</a> </li> … -
No module named 'rest_framework' on pythonanywhere.com
I'm trying to host my Django app on https://pythonanywhere.com I'm am getting the following error : ModuleNotFoundError: No module named 'rest_framework' I tried pip install djangorestframework pip3 install djangorestframework but its is still showing error. I also tried pip freeze and found djangorestframework==3.13.1 in the list. >>> import rest_framework also works fine. I ran my project locally and also it in a new virtual env, it worked fine. Installed same requirements.txt on pythonanywhere but still the same error. This is bugging me for a long time! please help here is my error log file: 2021-12-22 10:59:23,012: Internal Server Error: / Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/base.py", line 167, in _get_response callback, callback_args, callback_kwargs = self.resolve_request(request) File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/base.py", line 290, in resolve_request resolver_match = resolver.resolve(request.path_info) File "/usr/local/lib/python3.8/dist-packages/django/urls/resolvers.py", line 556, in resolve for pattern in self.url_patterns: File "/usr/local/lib/python3.8/dist-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.8/dist-packages/django/urls/resolvers.py", line 598, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python3.8/dist-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.8/dist-packages/django/urls/resolvers.py", line 591, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, … -
takes 1 positional argument but 2 were given error for dict
how to add two dict in cs list I want to add two dictionaries to the cs list in the addcoursess function, but it gives an error Text error: takes 1 positional argument but 2 were given mainlist: cs = [ { "title": "Python", "teacher": "Amiri", }, { "title": "HTML", "teacher": "Dehyami", }, { "title": "PHP", "teacher": "Enayati" } ] class User: def __init__(self, fisrtname, lastname): self.fname = fisrtname self.lname = lastname def fullname(self): print(f"my fullname is {self.fname} {self.lname}") class Student(User): def __init__(self, fisrtname, lastname, email): super().__init__(fisrtname, lastname) self.email = email self.coursess = [] def fullname(self): print("i am an student") super().fullname() def printcoursess(self): if self.coursess: for course in self.coursess: print("Coursess : " + course["title"]) else: print("There is no course") Here is the class in which it is error class Teacher(User): def __init__(self, fisrtname, lastname, code): super().__init__(fisrtname, lastname) self.code = code def addcoursess(item): dict = {} dict.update(item) cs.append(dict) print(dict) def fullname(self): print("i am an teacher") super().fullname() t1 = Teacher("abolfazl", "zaker", 3223) addcoursess function here t1.addcoursess({"title": "Java", "teacher": "ganjeali"}) print(cs) -
django left join sql to django orm
i only write sql, django orm is so-so,how to sql convert to django orm? sql SELECT ct.id, ct.nid, ct.`status`, ct.create_time, bp.id as program_id FROM `ct_task` as ct JOIN program as bp on ct.hash_code=bp.hash_code ORDER BY ct.id DESC LIMIT 0,10 orm class CTask(models.Model): hash_code = models.CharField(max_length=50, null=True, db_index=True) class Program (models.Model): hash_code = models.CharField(max_length=50, null=True, db_index=True) -
How to filter is_active product by Backward relationship in Django templates?
{% for category in categories %} {% for product in categories.product_set.all %} <h1> {{ product.name }} </h1> {% endfor %} {% endfor %} I want to show filter products(Those are is_active) that belong to a category in Django template. -
Django ORM filter then join on same column
Fairly new to Django, a bit lost... My objective : I these models : class IndicatorValue(models.Model): my_obj = models.ForeignKey("MyObject", on_delete=models.CASCADE) type = models.IntegerField() value = models.FloatField( null=True, blank=True, db_index=True) class MyObject(models.Model): date = models.DateTimeField("start_date", db_index=True) I want to get a list of IndicatorValue (value and type) for a MyObject that: has date > X has one indicator value of type Y that is above Z What I would do in SQL: In SQL, I would do something like : SELECT iv2.type, iv2.value FROM MyObject m JOIN IndicatorValue iv1 on m.pk = iv1.object_pk and iv1.type = Y and iv1.value > Z JOIN IndicatorValue iv2 on iv1.object_pk = iv2.object_pk WHERE m.date > X What i do I managed to do it with a loop as such: values_ok = IndicatorValue.objects.filter(type=Y).filter(value__gt=Z) for val in values_ok: print(val.my_obj.indicator_set.all()) but this is extremely slow as I suppose the each val.my_obj.indicator_set.all() fetches from the db. How would I fetch all the data I want in one go AND how do I access it ? (I have seen sometimes logging the sql queries that it does the double join but it creates an alias for the table - T5 for instance - and I don't know how to get … -
Unable to serialize custom boolean fields from models AbstractUser in django rest framework
I am unable to serialize custom model booleanfields is_subuser, is_student in django rest framework, even if i try to post using postman still i am unable, but i am able to see this two fields in django admin backend. models.py class User(AbstractUser): is_school = models.BooleanField('school status',default=False) is_student = models.BooleanField('student status',default=False) is_subuser = models.BooleanField('subuser status',default=False) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = "__all__" -
How to create a notification about adding a record to a database table in django?
A parser with a separate database is connected to django. How to make sure that you receive a notification about adding a record to the database in the admin panel? DB = Sqlite my models.py from django.db import models class WyrestormItem(models.Model): article = models.TextField(blank=True, null=True) name = models.TextField(blank=True, null=True) description_min = models.TextField(blank=True, null=True) description_max = models.TextField(blank=True, null=True) features = models.TextField(blank=True, null=True) specifications = models.TextField(blank=True, null=True) image_count = models.IntegerField(blank=True, null=True) image_links = models.TextField(blank=True, null=True) class Meta: managed = True db_table = 'wyrestorm_items' def __str__(self): return self.name -
How can I return image address to Django template from a function of the file views.py?
I need to display an image using Django templates but don't know how the "image address" will be returned from the function of the file views.py The image address will be stored according to the "id" of the project (a project has an image associated with it). Here is the function of the views.py file that I am writing:- def file_path(request, awp_id): Component_Progress_Update_inst = get_object_or_404( Component_Progress_Update, pk=awp_id) filepath = Component_Progress_Update_inst.Supporting_documents.name filepath = "/media/"+filepath print(filepath) # Returning the file path return HttpResponse(filepath) Following is the image tag, I am writing in HTML file:- <img src="{% url 'component_progress:file_path' awp.id %}" alt="Supporting image" width="200" height="200"> But the image is not getting displayed, instead of the image this "alt text" is getting printed. While I have tried displaying the image directly -> By directly writing that address in image "src". -
DRF and TensorFlow in Production WSGI. How to load models only once for all requests
I've created an API using the Django Rest Framework. The API uses a model for object classification using TensorFlow. The initial load of TensorFlow (import tensorflow as tf) can take time to instantiate (around 30 seconds), thankfully I only need them once and then the rest of my application can make use of accessing the pre-loaded model. Locally, I solved this issue by importing TensorFlow and my models just once during Django's start-up in settings.py, for example: import tensorflow as tf MODEL = tf.keras.models.load_model(BASE_DIR /'saved_model/') This allows me to call and reuse the model in my views/serializers without having to re-import or load them on every request again, for example: In serializers.py: # Get Model model = settings.MODEL model.predict(SOMEPADDEDVALUE) Everything works well in my local development (using runserver). However, I would like to move my Django API to production and I'm worried about the above approach! I will be using a WSGI server which I believe will use Multi-Threading (or multiprocess I get these confused) and the initial loading of my models will be duplicated on every request (I think) meaning the API will be unusable. I'm sure I'm not the first to come across this issue using TensorFlow saved … -
Visual Studio Code suggestions are gone
{ "editor.formatOnSave": true, "python.formatting.provider": "black", "python.linting.pylintEnabled": true, "python.linting.enabled": true, "python.linting.lintOnSave": true, "[python]": { "editor.defaultFormatter": "ms-python.python" }, "tabnine.experimentalAutoImports": true, "vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue", "python.pythonPath": "", "files.associations": { "*.html": "html", "**/templates/**/*.html": "django-html", "**/templates/**/*": "django-txt", "**/requirements{/**,*}.{txt,in}": "pip-requirements" }, "editor.quickSuggestions": true, "html.suggest.html5": true, "html.autoClosingTags": true, "emmet.includeLanguages": {"django-html": "html"}, "emmet.showAbbreviationSuggestions": true, "editor.suggestSelection": "first", } this is inside of my vsc settings.py i am working with django and launguage mode is Django-Templates if i type div or for i dont het any suggestion or autocomplete also in .py i dont see any suggestions would anybody please give me help? -
What is the use case for Django's on_commit?
Reading this documentation https://docs.djangoproject.com/en/4.0/topics/db/transactions/#django.db.transaction.on_commit This is the use case for on_commit with transaction.atomic(): # Outer atomic, start a new transaction transaction.on_commit(foo) # Do things... with transaction.atomic(): # Inner atomic block, create a savepoint transaction.on_commit(bar) # Do more things... # foo() and then bar() will be called when leaving the outermost block But why not just write the code like normal without on_commit hooks? Like this: with transaction.atomic(): # Outer atomic, start a new transaction # Do things... with transaction.atomic(): # Inner atomic block, create a savepoint # Do more things... foo() bar() # foo() and then bar() will be called when leaving the outermost block It's easier to read since it doesn't require more knowledge of the Django APIs and the statements are put in the order of when they are executed. It's easier to test since you don't have to use any special test classes for Django. So what is the use-case for the on_commit hook? -
How do i display information created by my powershell script onto my website
im a 14 y/o coder trying to create a website which can display some information . Link for code https://github.com/Aadishshele/Questionable/tree/main/Question In the powershell script, it gets the pc information and displays it onto a html website (X.html). Along with this i have a login script which takes user input and displays it onto a screen(Login.html). I want to display the pc information onto the same page as the display of the user input. Can anyone guide me on how to be able to do it?