Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get top n values of multiple columns after a group_by in django
qs = models.Stats.objects.all().values('player_id').annotate(**player_stats) I have a GROUP_BY with aggregation over multiple columns, see above. In my case that produces a result set of 8523 elements. [{'player_id': 1, 'abc': 205.0, 'def': 53.0, 'ghi': 37.0, 'jkl': 151.0, 'mno': 2.0, 'pqr': 959.0, ...}, {'player_id': 2, ...}, {'player_id': 3, ...}, ...] I want to get the top n players of different categories now, my first naive approach was to order_by that result set for every key i want o get the top n players for. qs.order_by('-abc)[:5], qs.order_by('-def)[:5] That is pretty slow because it hits the database with the full initial GROUP_BY query every time which is pretty heavy itself. In the end i just need the top 5 for each category ( abc, def, ghi ...), e.g. [{'player_id': 1, 'abc': 205.0}, {'player_id': 477, 'abc': 202.0}, {}, {}, {}] My guess is i can somehow achieve that with Djangos Window functions in a way more efficient manner, but i'm a little bit lost. -
Get Logged user, while updating Model User with UpdateView in Django
new to Django here building my first project. I´m using Django authentication and when user is logged, I show in a template panel the logged user using <li> <a style="color: wheat;" href="#"><i class="fi-torso"></i>{{user.full_name}}</a> <ul class="menu vertical" style="background-color:rgb(51,51,51); border-color: wheat;"> <li><a href="{% url 'users_app:user-logout' %}">Cerrar Sesión</a></li> </ul> </li> The thing is that logged user can modify other users attributes through UpdateView. So when I select user for updating (context user now is the user that is going to be updated), and I access Modify user template, in my panel instead of seeing logged user, I see the user that is being modify. How can I diferenciate this? I understand why this is happening, but haven´t found how to solve it -
How to check spyder versions in windows command prompt?
Please provide commands for checking Spyder IDE , Python IDLE, Atom IDE,SublimeText3 versions in windows command prompt -
JS fetching current data after posting form data
I am trying to create a single page application, but I am having problem getting the latest data after redirecting from the compose-form to the list of sent emails page. I get the previously loaded emails instead. I have to click the sent button, so as to update the list. Any solutions The html code is <h2>{{ request.user.email }}</h2> <button class="btn btn-sm btn-outline-primary" id="inbox">Inbox</button> <button class="btn btn-sm btn-outline-primary" id="compose">Compose</button> <button class="btn btn-sm btn-outline-primary" id="sent">Sent</button> <button class="btn btn-sm btn-outline-primary" id="archived">Archived</button> <a class="btn btn-sm btn-outline-primary" href="{% url 'logout' %}">Log Out</a> <hr> <div id="emails-view"> </div> <div id="compose-view"> <h3>New Email</h3> <form id="compose-form"> <div class="form-group"> From: <input disabled class="form-control" value="{{ request.user.email }}"> </div> <div class="form-group"> To: <input id="compose-recipients" class="form-control"> </div> <div class="form-group"> <input class="form-control" id="compose-subject" placeholder="Subject"> </div> <textarea class="form-control" id="compose-body" placeholder="Body"></textarea> <input type="submit" class="btn btn-primary mt-2" value="Send" id="sendButton"/> </form> </div> The JS code // Use buttons to toggle between views document.querySelector('#inbox').addEventListener('click', () => load_mailbox('inbox')); document.querySelector('#sent').addEventListener('click', () => load_mailbox('sent')); document.querySelector('#archived').addEventListener('click', () => load_mailbox('archive')); document.querySelector('#compose').addEventListener('click', compose_email); //My added events // To initiate post request, when posting the mail document.querySelector('#compose-form').addEventListener('submit', post_email); // By default, load the inbox load_mailbox('inbox'); }); var state; function compose_email() { // Show compose view and hide other views document.querySelector('#emails-view').style.display = 'none'; document.querySelector('#compose-view').style.display = 'block'; … -
python - django - local variable referenced before assignment django error
I am at my wit's end, I have no idea what may cause that issue. The only change I've made was add the loginquiredmixins to my class-based views. Once I started stylising the login page I seem to have broken something, but I have no idea what exactly, which is a weird idea to have, what issue could CSS or some HTML cause, right? I tried to assign the variables before the if statement and set it to null but that seems not to work properly as it throws an error regardless. I am using the basic django authentication system. The exact error I am getting is - local variable 'course' referenced before assignment Environment: Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login Django Version: 3.0.7 Python Version: 3.7.3 Installed Applications: ['mainpage.apps.MainpageConfig', 'quiz.apps.QuizConfig', 'courses.apps.CoursesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\m\AppData\Local\Continuum\anaconda33\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\m\AppData\Local\Continuum\anaconda33\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\m\AppData\Local\Continuum\anaconda33\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\m\AppData\Local\Continuum\anaconda33\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\m\AppData\Local\Continuum\anaconda33\lib\site-packages\django\contrib\auth\mixins.py", line 52, in dispatch return super().dispatch(request, … -
How to get the user's username and other parameters instead of just 'id' when using django.core.serializers?
Hey guys I want to get the user's username instead of id from the below code when I use django's serializer method, also want to know the possibilities of getting their profile pictures as well. This is the code. This method is being used with django-channels for a simple chat system. def get_chat_list(self, user): try: chats = Chat.objects.by_user(user).order_by('-timestamp') chat_list = serialize('json', chats, fields=('first_user', 'second_user', 'timestamp')) payload =json.loads(chat_list) # print(payload) return payload except Exception as e: print('Exception: ', str(e)) return None How can I get the first_user's and second_user's username and profile images? Thanks in advance. -
Django subqueries & aggregates
I have three models - Patient, Prescription and Medicine. A Patient can have zero or more Prescriptions and a Prescription can have zero or more Medicines. Medicine has a duration field indicating the days for which the medicine is to be taken. If we have say, two Prescriptions with two Medicines each with durations of 15, 15 and 15, 30 respectively, then the maximum prescription duration for the 2 Prescriptions are 15 and 30 respectively. And the total medication duration for that Patient is 15 + 30 = 45. Now I want to filter the Patient queryset to find all Patients whose total medication duration is at least a certain specified value. Following is the code (using Django 3) I am trying. But, taking the above example, the total medication duration I get is 30, not 45. from django.db import models from django.db.models import Subquery, OuterRef, Max, Sum class Patient(models.Model): name = models.CharField(max_length=300) # ... class Prescription(models.Model): patient = models.ForeignKey( Patient, related_name="prescriptions" on_delete=models.CASCADE ) # ... class Medicine(models.Model): prescription = models.ForeignKey( Prescription, related_name="medicines" on_delete=models.CASCADE ) duration = models.PositiveIntegerField() # ... def get_patients_with(minimum_medication_duration=365): patient_qs = ( Patient.objects .annotate(total_medication_duration=Subquery( Prescription.objects .filter(patient=OuterRef('pk')) .values('patient__pk') .annotate(max_prescription_durations=Subquery( Medicine.objects .filter(prescription=OuterRef('pk')) .values('prescription__pk') .annotate(max_duration=Max('duration')) .values('max_duration') )) .annotate(total_medication_duration=Sum('max_prescription_durations')) .values('total_medication_duration') )) … -
Django Web Scraping
I have a Django project that I am working on, to scrape data from a website and display it on the Django page. The page however takes about 10 seconds to load, because accessing the data from another website isn't quick. My solution to this would be to create a model that stores the data, then updates itself in the background, but I don't know how to execute this. I am also open to other options, I'm pretty new at this :) This is currently what my code looks like, which is too slow: from django.shortcuts import render import requests, json def getNums(): from bs4 import BeautifulSoup import time, urllib.request, requests url = "https://www.worldometers.info/coronavirus/" response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") numberContainers = soup.select(".maincounter-number") spanTags = [] for container in numberContainers: spanTags.append(container.findChildren("span")) numbers = [] for container in spanTags: numbers.append(container[0].decode_contents()) return numbers def homeView(request): numbers = getNums() cases = numbers[0] deaths = numbers[1] recovered = numbers[2] context = { "cases": cases, "deaths": deaths, "recovered": recovered, } return render(request, "home.html", context) -
Running executable backgroung program inside server
I'm an intern in a laboratory in my college that works with air quality, and they want me to improve their website that runs one of the programs that air quality researchers use (I think that the program is written in RUST). The way it works right now is that the user uploads some necessary files to the webapp (that is written in Django btw) and then the webapp calls this program, that runs on the server with the uploaded files. The problem is that if the user leave or refresh the page, the background program will stop. I have never dealt with this concept of running other executables in the background of the server, so I'm having some problems understanding it all. I came across the "Celery" package for python, but it seems really hard to implement and I was wondering if there was any other ways of doing this. -
Django 3.1.7 query parameter separators
With the change in Django 3.1.7 to not allow using ; as a default query parameter separator, what is the suggestion moving forward? Is there something else that should be used instead? Where does one specify which query param separators are permitted? There are the release notes for this version. -
Use python's mock patch.object to check if a functions is called
I need to assert if a function is called @requests_mock.Mocker() def test_api_mca_payment_confirmation_call_db_log(self, mocker): mocker.register_uri('GET', requests_mock.ANY, status_code=200, text='test') with patch.object('__name__', 'db_log') as m: r = api_payment_confirmation(txn_no=900) m.assert_called_once() The problem is on the first patch.object parameter, what to put there if my db_log function is not inside any class. It works if i put a db_log function inside a class eg class Sample: @static_method def db_log(): pass And change line to patch.object('__name__', 'db_log') as m: How can i do the same thing for functions outside class -
RegexValidator didn't catch violation of regex
Django 3.1.7 class RenderedCssFile(models.Model): css_pattern = r".*-\d+\.css$" regex_validator = RegexValidator(regex=css_pattern, message=gettext("File name must follow: ") + css_pattern, ) file_name = models.CharField(max_length=255, verbose_name=gettext("File name (eg. main-1.css"), validators=[regex_validator], ) Could you help me understand why a file called 'bootstrap.css' has managed to upload? I estimated it to fail, but it uploaded. I've made a mistake somewhere. My regex: https://regex101.com/r/N5aL0C/1/ I need that only bootstrap-1.css or the like should be accepted. -
Django Signals: Can't Use For Loop?
When i remove the for loop in the signals then it works (creates an object properly) but when i use the for loop it should create an object for each post in the Collection object but this doesn't work. It doesn't even create an object of the Collection_List_Item model. Is there a reason why this for loop doesn't work? Is there a way to work around this? models class Collection(models.Model): posts = models.ManyToManyField(Post, related_name='collection_posts', blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) collection_name = models.CharField(max_length=100) collection_description = models.CharField(max_length=1000, blank=True) collection_likes = models.ManyToManyField(User, related_name='liked_collections', blank=True) collection_image = models.ImageField(upload_to="images/") private = models.BooleanField(default=False) follows = models.ManyToManyField(User, related_name='collection_follows', blank=True) def __str__(self): return self.collection_name class Collection_List_Item(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) collection = models.ForeignKey(Collection, on_delete=models.CASCADE, null=True) saved = models.BooleanField(default=False) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) def __str__(self): return self.collection.collection_name signals: @receiver(post_save, sender=Collection) def create_collection_list_item(sender, instance, created, **kwargs): if created: for i in instance.posts.all(): collection_list_item = Collection_List_Item.objects.create(collection=instance, user=instance.author, post=i) collection_list_item.save() -
Performance issues with django-storages + CloudFront
I'm using S3 Buckets for static and media files of my Django app. I have AWS CloudFront "in front" of the Buckets and I have setup django-storages in order to use this CDN to serve me my files. However, my requests are taking too long. It is worth mentioning that I am using HyperlinkedModelSerializer and VersatileImageField. I would expect that my files were retrieved by the CDN but it looks like my app is using boto3 to actually download the files from S3 (and I think this is happening during serialization). Here's some information from cProfile: ncalls tottime percall cumtime percall filename:lineno(function) 174 0.004 0.000 17.172 0.099 /MyProjectPath/env/lib/python3.8/site-packages/storages/backends/s3boto3.py:515(exists) 61 0.003 0.000 16.586 0.272 /MyProjectPath/env/lib/python3.8/site-packages/boto3/s3/inject.py:723(object_download_fileobj) 61 0.001 0.000 16.582 0.272 /MyProjectPath/env/lib/python3.8/site-packages/boto3/s3/inject.py:624(download_fileobj) 62 0.003 0.000 57.723 0.931 /MyProjectPath/env/lib/python3.8/site-packages/rest_framework/serializers.py:507(to_representation) 62 0.000 0.000 57.687 0.930 /MyProjectPath/env/lib/python3.8/site-packages/versatileimagefield/serializers.py:53(to_representation) 62 0.000 0.000 57.687 0.930 /MyProjectPath/env/lib/python3.8/site-packages/versatileimagefield/serializers.py:42(to_native) 62 0.003 0.000 57.686 0.930 /MyProjectPath/env/lib/python3.8/site-packages/versatileimagefield/utils.py:220(build_versatileimagefield_url_set) I don't think the app should be contacting the S3 Buckets directly. Has anyone experienced this? Could this be a because of a misconfiguration or is there any known issue related to DRF/django-storages/VersatileImage that would affect performance this badly? -
How to create two type of users in a django website, re-writting authentication back end
So, this is how i am trying to create the two models: class UserManager(BaseUserManager): def create_user(self, email, username, year, branch, rollNo, password=None): if not email: raise ValueError("Users must have an email") if not username: raise ValueError("Users must have a username") if not year: raise ValueError("Users must specify an year") if not branch: raise ValueError("Users must specify a branch") if not rollNo: raise ValueError("Users must have a roll number") user = self.model( email=self.normalize_email(email), username=username, year=year, branch=branch, rollNo=rollNo ) user.set_password(password) user.save(using=self._db) return user def create_guest(self, username, college, year, email, password=None): if not username: raise ValueError("Please give a valid username") if not college: raise ValueError("Please provide your college") if not year: raise ValueError("Specify your year") if not email: raise ValueError("A valid email needs to be provided") user = self.model( email = self.normalize_email(email), username = username, year = year, college = college ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, year, branch, rollNo, password): user = self.model( email=self.normalize_email(email), username=username, year=year, branch=branch, rollNo=rollNo, password=password ) user.is_admin = True user.is_staff = True user.is_superuser = True user.set_password(password) user.save(using=self._db) return user class GuestUser(AbstractBaseUser): email = models.EmailField(unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date_joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last_login', auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) … -
How to use two different databases in Django? (SQLite and MongoDB)
For my project, I'm trying to set up two different databases in Django. These databases are SQLite and MongoDB. What I'm trying to do is I'm trying to hold user data in SQLite and for big data, I want to use MongoDB. After so many searches on the internet, I couldn't understand how to do it. I just did this little code in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': str(BASE_DIR / 'db.sqlite3'), }, 'bigdata_db' : { 'ENGINE' : 'mypackage.backends.mongodb', 'NAME' : 'bigdata_db', 'HOST' : '', } Please someone could help me. I'm really trying so hard to understand but it's so complicated for me. Also, in Django SQLite came already set up but here the main issue is how to set up MongoDB and connected two of them. -
Transmit a param into its validator and make migrations?
Django 3.1.7 I've transmitted a param to its validator: class RenderedCssFile(models.Model): char_pattern = r".*-\d+\.css$" file_name = models.CharField(max_length=255, verbose_name=gettext("File name (eg. main-1.css"), validators=[lambda value: GeneralValidator. validate_charfield_against_pattern( value, RenderedCssFile.char_pattern), ], ) I was very glad. But only before migrations were made: Migrations for 'staticassets': staticassets/migrations/0001_initial.py - Create model RenderedCssFile - Create model PhpFile - Create model JsFile - Create model CssFile Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/commands/makemigrations.py", line 182, in handle self.write_migration_files(changes) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/commands/makemigrations.py", line 219, in write_migration_files migration_string = writer.as_string() File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/db/migrations/writer.py", line 141, in as_string operation_string, operation_imports = OperationWriter(operation).serialize() File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/db/migrations/writer.py", line 99, in serialize _write(arg_name, arg_value) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/db/migrations/writer.py", line 51, in _write arg_string, arg_imports = MigrationWriter.serialize(item) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/db/migrations/writer.py", line 271, in serialize return serializer_factory(value).serialize() File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/db/migrations/serializer.py", line 37, in serialize item_string, item_imports = serializer_factory(item).serialize() File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/db/migrations/serializer.py", line 199, in serialize return self.serialize_deconstructed(path, args, kwargs) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/db/migrations/serializer.py", line 86, in serialize_deconstructed arg_string, arg_imports … -
Can I control how often the pre-ping connection check is done in SqlAlchemy connection pooling?
Environment / usage case info I have a SqlAlchemy django-postgrespool2 connection pool used to connect to a PostgreSQL database. Problem I'm considering using the pre-ping feature in my SqlAlchemy connection pool. However, I read that the pre-ping check is done for every pool connection checkout. I have done some tests, to me this checkout seems to occur for every SQL command I send to the database. I'm concerned all those pre-ping checks will cause a big overhead/delay if the check is made for every SQL command sent to the database. Question Is there a way to configure how often or after what time the pre-ping check should be made? Or do I have to implement my own solution to customize how often the connection is checked? How? Thanks! -
How should I develop the front-end? (help!) [closed]
So basically I have this idea for a web application where users can upload 'posts' which than will be upload to the 'feed'. So pretty much like all forums, social media applications, etc. Just like for example Reddit, I want the user to have specific options in de 'make-a-post-template' that he/she can fill in. It's a pretty complicated concept if I go in the dept of it, but my real question here is: How should I develop the front-end? Here are some key-points that I take in for the decision: I have never used a front-end framework before (basic knowledge of Javascript). But I'm willing to learn if there is much benefit to gain from it. It's going to be a forum website like Reddit, but for a specific audience. I want to use Django Please help me out here, I'm worried that if I don't use a front-end framework, that the speed of the website will dramatically decrease, and because I'm using diffrent content blocks, to create a 'dashboard' kind of style, that something like React will be very suitable for this. Take a look at the images to get some idea of how it's going to work and … -
How to use existing mysql DB along with its migrations in sql, in the Django? What changes will need to do in the django for using the mysql db?
I am already having one mysql database with a lot of data, of which tables and migrations are written in sql. Now I want to use the same mysql database in django so that I can use the data in that database.I am expecting that there will not be need for making the migrations as I am not going to write the models in Django again, also what will be the changes/modification I will have to do. For eg: as in middlewares?. Can anyone please help me in this? -
Asynchronous computation and save in django 3 models
I have a problem making part of my models asynchronous in Django 3. This is my models.py: class ModelImages(models.Model): case = models.ForeignKey(Case, on_delete=models.CASCADE, related_name="slice_img") img = models.ImageField(editable=False) #other def get_slices(instance): # operations return images_array_list def process_3d_image(sender, instance, created, **kwargs): if created: imgs = get_slices(instance) for img in imgs: # other operations case_img = ModelImages(case=instance, img=name) with transaction.atomic(): case_img.save() post_save.connect(process_3d_image, sender=Case) The code is longer but I reported only the crucial parts. It works correctly but I want to make 'process_3d_image' function asynchronous. I tried Celery, Trio, and others without any result. How could I do it? -
Docker containing a Django application a not saving database after stopping container
I have build a Django application with SQLite database. The database is reinitialized and migrated every time the container is started using docker-compose up losing all the previous data. It also not creating db or any other files. Using the latest version of docker. -
How to display a list of posts in a list of categories in Django
I am looking for my web page to display a list of categories and a list of each post within the category. For example: However, it is looping through and displaying each category and associated post separately, like this: Here is Template: <ul> {% for p in object_list %} <li> {{p.category.name}} <ul> <li> {{p.title}} </li> </ul> </li> {% endfor %} </ul> Model class Category(models.Model): name = models.CharField(max_length=200, blank=True, null=True) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category', null=False) Views class CategoryList(ListView): template_name = 'category_list.html' def get_queryset(self): return Post.objects.all().select_related('category') -
Overriding get() method in Django UpdateView gives 'str' has no attribute get error
I have a Stats model which is related to Django User model with a OneToOne Field. I have an UpdateView: class StatsUpdateView(UpdateView): model = Stats fields = ('stat1', 'stat2', 'stat3') It works fine, but any User is allowed to modify the Stats related to any User, I want a User to onlyupdate the Stats related to him. So I override the get() method in StatsUpdateView like this: def get(self, *args, **kwargs): if self.request.user != Stats.objects.get(pk=kwargs['pk']).user: #checks if the user logged in is the same user related to the Stats with the onetoone field. Works fine. return redirect('homepage:home') else: # if the user match, he can access the update view for his own stats print('user match') return reverse('user:updatestats', kwargs={'pk': kwargs['pk']}) The code runs fine until the else statement, 'user match' gets printed into the console but I get this error while running the server: 'str' object has no attribute 'get' Here's the path: path('updatestats/<int:pk>/', StatisticheUpdateView.as_view(), name='updatestats') -
Logging Output for Session on Webclient
I'm using Django to deploy some of my calculations-modules and allow registered and unregistered users to make use of them. Now I happen so see on the serverlogs sometimes invalid files are uploaded and during the process I'm able to fix it to some degree. These calculation-modules are separated from the Django-Project, but still on the same server. My first thought would be to pass on logging-variables through them and return them in the end of the calculation in the server response. This seems to be a dirty and rather invasive solution as everything is basically protocolled with with the basic logging. Any of my methods would with that get an additional logging-variable. Apparently Output log file through Ajax in Django seems to somewhat fit to what I am looking for but this appears only to show the full logs and not by session (given the case one user has two sessions). The modules in the backend don't have any session-ID, but it wouldn't be too difficult to add it just in the constructors. The Ajax-Module on the Client doesn't seem to be the problem (plenty of sources, like: Django - How to show messages under ajax function), but how …