Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display the number of students who has enrolled in the course the instructor has created
I am building a website where the instructor can create courses and students can enroll to the courses. I am facing a problem when displaying the number of students that has enrolled to the courses that an instructor has. I am not sure how to get the number of students that has enrolled to the courses that the instructor has. Please help T.T models.py class Course(models.Model): user = models.ForeignKey(Users, on_delete = models.CASCADE) media = models.ImageField(upload_to = 'media/course') title = models.CharField(max_length=300, null = False) subtitle = models.CharField(max_length=500, null = False) description = models.TextField(max_length=5000, null = False) language = models.CharField(max_length=20, null = False, choices=LANGUAGE) level = models.CharField(max_length=20, null = False, choices=LEVEL) category = models.CharField(max_length=30, null = False, choices=CATEGORY) subcategory = models.CharField(max_length=20, null = False) price = models.FloatField(null = True) roles_responsibilities = models.TextField(max_length=2500, null = False) timeline_budget = models.TextField(max_length=250, null = False) req_prerequisite = models.TextField(max_length=2500, null = False) certificate = models.CharField(max_length=5, null = False, choices=CERTIFICATE) slug = AutoSlugField(populate_from='title', max_length=500, unique=True, null=True) class Enrollment(models.Model): student = models.ForeignKey(User, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) def __str__(self): return "%s %s" % (self.student, self.course) views.py def instructorDashboard(request): user = Users.objects.all() user_id = Users.objects.get(user_id=request.user) course = Course.objects.filter(user = user_id) course_count = course.count() context = {'user':user, 'course_count': course_count} return render(request, … -
Image handling with django-summernote
The image uploads and appears on the text editor but when I post, the image is not on the page. Inspecting the page, I find that the tag is the but no source. settings.py DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' LOGIN_URL = 'users:login' import django_heroku django_heroku.settings(locals()) if os.environ.get('DEBUG') == 'FALSE': DEBUG = False elif os.environ.get('DEBUG') == 'TRUE': DEBUG = True MEDIA_URL = '/media/django-summernote/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/django-summernote/') SUMMERNOTE_THEME = 'bs4' X_FRAME_OPTIONS = 'SAMEORIGIN' -
PROTECT vs RESTRICT for on_delete (Django)
I read the django documentation about PROTECT and RESTRICT to use with "on_delete". PROTECT Prevent deletion of the referenced object by raising ProtectedError, a subclass of django.db.IntegrityError. Example: class MyModel(models.Model): field = models.ForeignKey(YourModel, on_delete=models.PROTECT) RESTRICT Prevent deletion of the referenced object by raising RestrictedError (a subclass of django.db.IntegrityError). Unlike PROTECT, deletion of the referenced object is allowed if it also references a different object that is being deleted in the same operation, but via a CASCADE relationship. Example: class MyModel(models.Model): field = models.ForeignKey(YourModel, on_delete=models.RESTRICT) To some degree, I could understand the difference between PROTECT and RESTRICT but not exactly so what is the difference between PROTECT and RESTRICT exactly? and when should I use them? -
How to retrieve value from through model using django-tables2?
I have the models below that allows users to create a playlist with many tracks associated to a playlist. I'd like to create a table with django-tables2 that shows 3 columns: the priority of the track, the artist and title in the playlist. How can I write the render_priority function to retrieve the priority value from PlaylistTrack model for the associated track for the playlist? models.py class Artist(models.Model): name = models.CharField(max_length=100) class Track(models.Model): artist = models.ForeignKey( Artist, blank=True, null=True, on_delete=models.SET_NULL, verbose_name="Artist", related_name="tracks", ) title = models.CharField(max_length=100, verbose_name="Title") class Playlist(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False ) name = models.CharField(max_length=50) tracks = models.ManyToManyField(Track, through="PlaylistTrack") description = models.TextField(blank=True, max_length=200) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) slug = AutoSlugField( populate_from="name", unique=True, editable=True, slugify=custom_slugify ) class PlaylistTrack(models.Model): track = models.ForeignKey(Track, on_delete=models.CASCADE, null=True) playlist = models.ForeignKey(Playlist, on_delete=models.CASCADE, null=True) priority = models.PositiveSmallIntegerField(default=1) class Meta: ordering = ["priority"] tables.py class PlaylistTable(tables.Table): def __init__(self, *args, **kwargs): super(PlaylistTable, self).__init__(*args, **kwargs) def render_priority(self): pass # get priority value from PlaylistTrack model for track in playlist priority = tables.Column( verbose_name="#" ) class Meta: model = Track fields = ( "priority", "artist", "title", ) -
Django - Can't retrieve Many to Many field from Queryset
I have the following code: exercises = Exercise.objects.filter(teacher=request.user.id).values('id', 'question', 'ans1', 'ans2', 'ans3', 'correct', 'unit', 'resol', 'theme', 'img') This works fine, but the "theme" is a Many to Many Field, the format returns { ..., theme: value } instead of { ..., theme: [value1, value2] } What should I implement to get the desierd format? -
Login in Django built in authentication system with Vue - What should I return after login(request, user)?
I am trying to develope a SPA with Vue in the frontend and Django (without REST framework) in the backend. My view requires the user to be logged in with the @login_required decorador. I also have the sign_in view to login the user, but I don't know what I should return to the frontend after the login(request, user). My views.py @csrf_exempt def signin(request): email = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=email, password=password) if user is not None: login(request, user) ??? @login_required @csrf_exempt def usinas(request): do stuff... -
action decorator not calling method in DRF?
so I have a route api/reviews it works fine for basic CRUD operations but according to DRF documentation, I can add extra actions to post, put, patch requests by using the @action decorator. the route is: POST domain/api/reviews data=irrelevent JSON # reviews/<uuid:id> && reviews # Provides CRUD + List interface for Reviews class ReviewView(viewsets.ModelViewSet): permission_classes = [IsPosterOrSafeOnly] queryset = Review.objects.all() serializer_class = ReviewSerializer pagination_class = Pagination @action(detail=False, methods=['post','put', 'patch'], serializer_class=ReviewSerializer) def rating(self, request): print("100: ", request) from what I understand the way this works is that when I do a post request to the reviews route it will do the post like it normally does and it will do the task in the action decorator. so I tried doing a post request to see if the code inside the 'rating' method gets run and it does not. I have tried setting detail to both True and False including the pk. nothing really seems to work. -
Issue connecting PostgreSQL db to Heroku
I am currently trying to deploy a Python/Django app to Heroku. The build was successful however, I am attempting make a migration to an established postgresql database to connect it to Heroku remote. When I run: heroku run python manage.py migrate I get the following error: ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? The Django environment is currently activated in my terminal screen. I ran python to get the version type then ran print(sys.path which showed the Django environment listed. Just for giggles I ran pip install django once again, where a message stating requirement already satisfied came up. So it looks like django is installed, my virtual environment is working, but I cannot make the migration for Heroku... Any advice appreciated. -
Django form field help_text rendering problem
I have the following template: {% if field.help_text %} <p class="helptext"> { field.help_text|safe }} </p> {% endif %} The problem is: help_text is being rendered outside the p tag for a password field. <p class="helptext"> </p> <ul> <li>...</li> <li>...</li> </ul> Am I doing something wrong? Am I missing something? How can I apply "helptext" class to the help_text provided by the passwordfield? -
Django: Instantiating a form in a custom class based view
This is my first post, and I am new to Django so go easy on me! I am trying to convert my function based views into class based views so I can reuse the views easily in other apps, and am struggling with instantiating a form inside the class. I have the following function based view: def object_create(request): def get_date(): today = datetime.datetime.now() enquiry_date = today.strftime("%d/%m/%Y") return enquiry_date initial_dict = { "account_handler" : request.user, "prep_location" : request.user.profile.location, "load_location": request.user.profile.location, "return_location": request.user.profile.location, "status":"Enquiry", "enquiry_date": get_date() } object_form = QuoteForm(request.POST or None, initial = initial_dict) context = { 'form': object_form, } if request.method == 'GET': return render(request, "rental_quotes/form.html", context ) # If we are saving the form if request.method == 'POST': if object_form.is_valid(): new_object = object_form.save() context = { 'object': new_object } found_count = Quote.objects.all().count() request.session['rental_quotes_current_index'] = (found_count-1) request.session['rental_quotes_found_count'] = found_count new_page = json.dumps({ 'url': reverse("rental_quotes-detail", args=[new_object.id]), 'index': found_count-1, 'found_count': found_count, 'content': render_to_string('rental_quotes/pages/detail.html', context) }) return JsonResponse(new_page, safe=False, status=200) else: return render(request, 'rental_quotes/form_block.html', context ) Which works fine. In my attempt at creating a class I can import into a class based view I have: class ObjectCreate(LoginRequiredMixin, View): def get_date(): today = datetime.datetime.now() enquiry_date = today.strftime("%d/%m/%Y") return enquiry_date def get (self, request): … -
urlpatterns wont match the url path
urlpatterns = [ path('cart', auth_middleware(CartViewAndAdd.as_view()) , name='cart'), path('viewcart', auth_middleware(CartOnlyView.as_view()) , name='viewcart'), ] <th><a href="/cart?product={{product.id}}&seller={{price.seller}}" class="btn btn-primary">Add to Cart</a></th> This code was working earlier. I seem to have messed with it. What could be wrong -
how to remember the selected radio button option in diango
i asked this question previously and didn't get any help/solution. so i'm asking again. i'm trying to make sure that even if the user refresh the page or goes back and comes back to that page, the radio button is still the same as what the user selects. N.B: the value of the radio button is saved in sessions <div class="col-md-1 ps-md-1"> <input class="align-middle h-100" type="radio" name="deliveryOption" id="{{option.id}}" value="{{option.id}}"> </div> Ajax $('input[type=radio][name=deliveryOption]').on('change', function(e) { e.preventDefault(); $.ajax({ type: "POST", url: '{% url "checkout:cart_update_delivery" %}', data: { deliveryoption: $(this).val(), csrfmiddlewaretoken: "{{csrf_token}}", action: "post", }, success: function (json) { document.getElementById("total").innerHTML = json.total; document.getElementById("delivery_price").innerHTML = json.delivery_price; }, error: function (xhr, errmsg, err) {}, }); }); my view def cart_update_delivery(request): cart = Cart(request) if request.POST.get("action") == "post": delivery_option = int(request.POST.get("deliveryoption")) delivery_type = DeliveryOptions.objects.get(id=delivery_option) updated_total_price = cart.cart_update_delivery(delivery_type.delivery_price) session = request.session if "purchase" not in request.session: session["purchase"] = { "delivery_id": delivery_type.id, } else: session["purchase"]["delivery_id"] = delivery_type.id session.modified = True response = JsonResponse({"total": updated_total_price, "delivery_price": delivery_type.delivery_price}) return response when i added a django templating if statement, it kinda work but the radio button is always remember on the last radio button when refreshed. {% for option in deliveryoptions %} <input class="align-middle h-100" type="radio" {% if deliveryoption == %} … -
Django Data Model / Database design problem
Quite new at database design and I'm trying to understand what will be the best way to design a database to be used in django. For a project management app for film vfx work I want to track all the versions and task assigned to artost. My problem is how to differentiate between different worflows keeping the same database. Typically the workflow for a Feature Film is: Project->Sequences->Shots->Tasks->Versions. while a workflow for a tv series is slightly different: Project->Season->Episode->Sequences->Shots->Versions So basically in the first case we don't need Entities / Models for Sesons and Episodes and shots will be contained directly in Sequences. What would be the best way to achieve this model? Should I make 2 apps for different workflows and copying the same classes into each app Models? thanks in advance. https://drive.google.com/file/d/1L3XwtvMhNM3AzotSiAE7yT495QTqBcVs/view?usp=sharing Obviously this simple code would not work as Episode is always need to be define: class Project(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Season(models.Model): name = models.CharField(max_length=2) project_id = models.ForeignKey(Project, on_delete=models.CASCADE) def __str__(self): return self.name class Episode(models.Model): name= models.CharField(max_length=3) season_id = models.ForeignKey(Season, on_delete=models.CASCADE) def __str__(self): return self.name class Sequence(models.Model): name = models.CharField(max_length=3) episode_id = models.ForeignKey(Episode, models.CASCADE) project_id = models.ForeignKey(Project, on_delete=models.CASCADE) def __str__(self): return self.name … -
Using cache invalidation for a user permission django
I am currently working on a cache for user permissions in Django. The structure for enabling users/organizations access to certain areas of the application looks like this: Meaning a User can either have access to a feature via his organization or as a user himself. What I want is a key-value cache that safes all the features a user/organization member has access to as a string. So whenever a user request access to a certain view the permission class first fetches all features for that user from the cache. I have implemented that as follows: class UserPermissionCache: def __init__(self): self.redis = StrictRedis( host=settings.REDIS_RATE_LIMITING_URL, port=settings.REDIS_RATE_LIMITING_PORT, db=settings.REDIS_RATE_LIMITING_DB, ) self.validation = datetime.now().strftime("%m%d%Y%H%M%S") def status_key(self, member): return f"user:features:{self.validation}:{member.uuid}" def set_user_features(self, user, key): features = Feature.objects.filter( Q(enabled_for_all=True) | Q(enabled_for_users=user) | Q(enabled_for_organizations=user.only_organization) ) result = FEATURE_STRING_SEPERATOR.join( feature.code for feature in features ) if not self.redis.set(key, result, settings.USER_FEATURES_TIMEOUT): logging.warning(f"Couldn't set features for user: {user.uuid}") return result def get_user_features(self, member): key = self.status_key(member) try: result = self.redis.get(key) except ConnectionError: logger.error( "ConnectionError, Failed to fetch feature permission for user", extra={"member": member.uuid}, ) return None if result is None: result = self.set_user_features(member, key) result = result.split(FEATURE_STRING_SEPERATOR) else: result = result.decode("utf-8").split(FEATURE_STRING_SEPERATOR) return result def reset_user_features(self, sender, **kwargs): for member in organization_members: … -
Converting to using URL router is causing a ImproperlyConfigured exception
I have been working through the Django Rest Framework tutorial and on the very last step I am encountering the error: Exception Type: ImproperlyConfigured. Exception Value: Could not resolve URL for hyperlinked relationship using view name "snippet-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. When trying to view either /settings/ or /users/ (visiting any user pages yields the same exception but with "user-detail" in place of "snippet-detail") as well as any specific indices of them, etc. All that works is root and login. All my code thus far has been working fine and I'm very confused as to why copy-pasting from the tutorial would yield such catastrophic results In comparing my snippets files with those available on the tutorial's repo I have not been able to find any significant difference (all that I've found is inconsistencies in whitespace). That being said, here is the code I'm using. snippets/views.py: from snippets.models import Snippet from snippets.serializers import SnippetSerializer, UserSerializer from rest_framework import generics, permissions from django.contrib.auth.models import User from snippets.permissions import IsOwnerOrReadOnly from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.reverse import reverse from rest_framework import renderers … -
How to save data from a webpage into Django database without using a form?
I am trying to save data from my webpage into my Django database. The data does not come from a form - I have built a web-based game with a timer and I would like to store the end value of the timer in my database for each game once the user presses the 'finish' button. The data doesn't come from a form as the timer increments automatically every second and stops when the finish button is pressed - how would i go about saving this to my django database? this is what the django model looks like: class Games(models.Model): username = models.ForeignKey(User, on_delete=models.CASCADE) startTime = models.DateTimeField(auto_now_add=True) solveTime = models.IntegerField() hintsCount = models.IntegerField() difficultyChoices = [ ('E', 'easy'), ('M', 'medium'), ('H', 'hard') ] difficulty = models.CharField(max_length=2, choices=difficultyChoices, default='M') so for example i would like to be able to send a POST request to the server with {timer: 300, hints:2} which can then be saved with the above model thanks :) -
Deployed django app error: Relation does not exist
I deployed a django app using a postresql database with Heroku. The app works perfectly on my local machine but when I want to create a user or to login using the deployed app, I run into the following error: ProgrammingError at /register/ relation "register_user" does not exist LINE 1: SELECT (1) AS "a" FROM "register_user" WHERE "register_user"... ^ Request Method: POST Request URL: https://the-gecko.herokuapp.com/register/ Django Version: 4.0.3 Exception Type: ProgrammingError Exception Value: relation "register_user" does not exist LINE 1: SELECT (1) AS "a" FROM "register_user" WHERE "register_user"... ^ Exception Location: /app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py, line 89, in _execute Python Executable: /app/.heroku/python/bin/python Python Version: 3.9.10 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages'] Server time: Mon, 21 Mar 2022 19:59:58 +0000 I believe this error has something do to with my postgres database, but I don't know what relevant code to share in that case. Please, let me know if you have any idea how to solve that issue. -
How to have Django *not* parse "{{variable}}" when using Jsrender?
I am building a Django template which will use jsrender in order to build out dynamic Javascript templates for html code. However, I find that when I put a Jsrender template in my code, Django flips out because Django parses anything between {{ and }} as a variable, and Jsrender uses this for its own variables. For instance, a template in Jsrender might look like: <script id="headerTemplate" type="text/x-jsrender"> <h1>{{:label}}</h1> </script> Django sees {{:label}} and tries to parse it, which leads to an error. Is there a Django block I can invoke which would make Django not parse any text within it? Or otherwise to escape a { character? -
Django : How should I correct this Form to display the data of the models in a dropdown list
I am Newbee in Django. I want to create a Form for a dropdown list. The Dropdown list should show different choices depending on User and the Models. So to get the data that I want to display in the dropdown list. I start to get the user ID. Then from the User ID, I get the list of ID clients that this user has access in the model "TblAadJntGroup". Finally I identify the client list by getting the correlation of this list of ID in the model "TblAadGroups". I write this form from the models that are listen below. It gets well the "id_client_list", but I do not know how to add it in the "forms.ChoiceField" after the init method. What should I change or improve Forms.py class SelectClient(forms.ModelForm): def __init__(self, *args, **kwargs) : self.user = kwargs.pop('user') super(SelectClient, self).__init__(*args, **kwargs) id_client_list = TblAadJntGroup.objects.filter(id_aaduser=self.user.id).values_list('id_aadgroup', flat=True) id_client_list = list(id_client_list) self.fields['ID_Customer'].queryset = TblAadGroups.objects.all().filter(id__in=id_client_list) class Meta: model = UploadFiles fields = ['ID_Customer'] client_list = forms.ChoiceField() models.py class TblAadJntGroup(models.Model): id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase. id_aadgroup = models.IntegerField(db_column='ID_AADGroup', blank=True, null=True) # Field name made lowercase. id_aaduser = models.IntegerField(db_column='ID_AADUser', blank=True, null=True) # Field name made lowercase. createdon = models.DateTimeField(db_column='CreatedOn', blank=True, null=True) # … -
processing image uploaded by createview in django
I am returning back to django after a while, and I am a bit confused on how I should go about processing images once they have been uploaded in createview class. So, I have this: class SomeModel(models.Model): full_name = models.CharField(max_length=200) email_simple = models.EmailField(max_length = 256) image = models.ImageField(upload_to='images') def __str__(self): return self.full_name class SomeModelForm(forms.ModelForm): """Form for the image model""" class Meta: model = FASModel fields = ('full_name', 'email_simple', 'image') <form role="form" action="{% url 'upload' %}" enctype="multipart/form-data" method="post">{% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> It works fine as in uploads the image, but, before redirecing to say an upload done page, I would like to postprocess this image using custom logic (such as resizing using ffmpeg and processing it further). Which method within CreateView can allow me to do this? or is there a more efficient way to approach this problem? Thank you. -
Problem with related objects in REST Framework
I have a simple django application with the following models: class Product(models.Model): __metaclass__ = ABCMeta title = models.CharField(max_length=50) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=100, unique=True) price = models.IntegerField() is_published = models.BooleanField(default=True) @abstractmethod def __str__(self): pass @abstractmethod def get_absolute_url(self): pass class SupplyType(models.Model): title = models.CharField(max_length=10) slug = models.SlugField(max_length=100, unique=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('supply_type_detail', kwargs={'slug': self.slug}) class Processor(Product): supply_type = models.ForeignKey(SupplyType, on_delete=models.CASCADE) cores_amount = models.IntegerField() threads_amount = models.IntegerField() technological_process = models.IntegerField() def __str__(self): return self.title def get_absolute_url(self): return reverse('processor_detail', kwargs={'slug': self.slug}) The corresponding serializers were written for them: class SupplyTypeSerializer(ModelSerializer): class Meta: model = SupplyType fields = '__all__' class ProcessorSerializer(ModelSerializer): class Meta: model = Processor fields = '__all__' depth = 1 The corresponding views were also written (I will give only the views of creation for an example): class ProcessorCreateAPIView(CreateAPIView): model = Processor serializer_class = ProcessorSerializer class SupplyTypeCreateAPIView(CreateAPIView): model = SupplyType serializer_class = SupplyTypeSerializer When I try to add "Supply Type" using POST request, it works successfully. However, when I try to add a processor like this: { "title": "Intel Pentium Gold G6400", "slug": "intel-pentium-gold-g6400", "price": 19690, "is_published" : true, "cores_amount": 2, "threads_amount": 4, "technological_process": 14, "supply_type": 1 } I get an error: django.db.utils.IntegrityError: null … -
how to display a pdf in django admin? instead of the link
models.py class Equipo(models.Model): CODIGO = models.CharField(primary_key=True, max_length=5 ) DESCRIPCION = models.CharField(max_length=50, default='') TITULO = models.FileField(upload_to = "Archivos/Titulos/", default='', blank=True) admin.py from django.contrib import admin from .models import Equipo class EquipoAdmin(admin.ModelAdmin): list_display = ('CODIGO', 'DESCRIPCION', 'TITULO') admin.site.register(Equipo, EquipoAdmin) I need to see something like this -
Why does django-wishlist require django-user-accounts dependency
How to I merge django-wishlist package with the user account. My head is doing in now. Worked on it for more than a day. https://github.com/dokterbob/django-wishlist https://github.com/pinax/django-user-accounts -
Permission error with Django logs in production
When trying to apply logging config to my Django project on the production server, the site returns a 502 gateway error and sudo journalctl -u gunicorn shows the following Permission denied: '/home/logs/MySite.log' error. The same config runs on the staging server and is working (using the same debug=false, gunicorn/nginx setup, not using any development settings like ./manage.py runserver or debug=true). The only difference I am aware of is that the staging server is served through http instead of https. Can anyone help fix the permissions error and to get logging running on production? Thanks in advance! Error -- Logs begin at Thu 2022-03-17 01:36:23 UTC, end at Sun 2022-03-20 22:41:48 UTC. -- Mar 20 22:40:00 mysite-prod gunicorn[419844]: File "<frozen importlib._bootstrap>", line 994, in _gcd_import Mar 20 22:40:00 mysite-prod gunicorn[419844]: File "<frozen importlib._bootstrap>", line 971, in _find_and_load Mar 20 22:40:00 mysite-prod gunicorn[419844]: File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked Mar 20 22:40:00 mysite-prod gunicorn[419844]: File "<frozen importlib._bootstrap>", line 665, in _load_unlocked Mar 20 22:40:00 mysite-prod gunicorn[419844]: File "<frozen importlib._bootstrap_external>", line 678, in exec_module Mar 20 22:40:00 mysite-prod gunicorn[419844]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed Mar 20 22:40:00 mysite-prod gunicorn[419844]: File "/home/MySite/VicMySite/wsgi.py", line 15, in <module> Mar 20 22:40:00 mysite-prod gunicorn[419844]: … -
How to get time and memory usage of each Django request?
I am new in Django and I am trying to get time and memory usage of request in it. I created middleware what doesn't work. import os import psutil import sys import time class MiddlewareStats: def __init__(self, request): self.get_response = request def __call__(self, request): self.mem = psutil.Process(os.getpid()).memory_info() self.start_time = time.time_ns() response = self.get_response(request) total = time.time_ns() - self.start_time mem = psutil.Process(os.getpid()).memory_info() diff = mem.rss - self.mem.rss response["X-total-time"] = int(total) response["X-total-memory"] = int(diff) return response It returns strange numbers. High probably because I didn't understand how it works. Thank you for your help. Also I read this question, but it doesn't work already.