Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
unable to use link to the admin page in django
i am using django 3.0.8 on python 3.7 and every time use the link to the admin page. i get this: this is the cmd console after i enter the admin page. this is the web page error my urls.py file and my settings.py file i am not finding any solutions online and any help would be appreciated. P.S i am using the database django comes with. the sqlite3 one. -
How do I initialize a django form with the previous input in a class based view?
It displays a form on the top and when you submit it, it will only show some of the Offer instances that fits the filters. It works fine, but every time I submit it, the form returns to the initial value. How can I stop that? My form uses GET and the view is class-based. Also, the __init__ in the form doesn't seem to be working. views.py class Search(ListView, FormMixin): model = Offer template_name = 'search.html' paginate_by = 20 form_class = SearchForm def get_queryset(self): self.form = SearchForm(self.request.GET) if self.form.is_valid(): data = self.form.cleaned_data qs = Offer.objects.all() if data['book'] != '0': qs = qs.filter(book_id=data['book']) qs = qs.filter(worn_degree__in=data['min_worn_degree']) qs = qs.filter(note_degree__in=data['min_note_degree']) return qs else: return Offer.objects.all() search.html {% extends 'base_generic.html' %} {% block content %} <form method="get"> {% csrf_token %} <table> {{ form.as_table }} </table> <br> <input type="submit" value="검색"> </form> {% if object_list %} {% for object in object_list %} <p>{{ object.book.title }}</p> <p>{{ object.seller }}</p> {% endfor %} {% else %} <p>There are no offers.</vp> {% endif %} {% endblock %} forms.py class SearchForm(forms.Form): def __init__(self, *args, **kwargs): super(SearchForm, self).__init__(*args, **kwargs) self.book = '0' self.min_worn_degree = 'abc' self.min_note_degree = 'abc' BOOK_CHOICE = tuple([('0', '모두')] + [(book.id, book.title) for book in Book.objects.all()]) book … -
Form booleanfield does not appear in request.POST data
I tried printing out all (key,value) pairs in a request.POST to extract the form data. I notice that a BooleanField, if not checked (i.e. set to True), is not included in request.POST. This is true even if the BooleanField is set with required=True. Is it possible to force the (key,pair) to be sent? For example, in this form below, if applied field is not checked when rendered, request.POST should still include applied off? When applied is checked, request.POST includes applied on. But without being checked, applied is not part of request.POST data. class ItemModifierForm(forms.Form): applied= forms.BooleanField(label='Trait A', required=True) -
Django: prefetch related: for loop: based on how we call for loop, the number of sql call varies
In django i am trying to understand prefetch: I have two for loop scenarios after prefetch symbollist = SymbolList.objects.prefetch_related('some_related_name')[0:10] for i in range(0,symbollist.count()): print(symbollist[i].some_related_name) Now it calls sql N+1 times where as symbollist = SymbolList.objects.prefetch_related('some_related_name')[0:10] for symbol in symbollist: print(some_related_name) this will call only two sqls Why so -
Django Can I change the Receive Charset specific View?
settings.py DEFAULT_CHARSET = 'UTF-8' views.py class OrderResult(viewsets.ModelViewSet): def create(self, request, *args, **kwargs): payload = request.data <<---- some string broken *** save to database i'd like to receive data with 'euc-kr' only in the above View. Is it impossible? I can't find it. -
How to fix find and Field 'id' expected a number but got '' error
I am trying to add a like button to my posts in a Django Project. I have made a model for the likes and included a value for it. In the template the post_id should be reflected in the views but for some reason it is showing an error. So, I have followed all the steps correctly but I am getting error: ValueError at /blogs/like Field 'id' expected a number but got ''. Here is the models.py class Post(models.Model): liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked') ...................................... @property def num_likes(self): return self.liked.all().count() LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike') ) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=10) date_liked = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.post) Here is the views.py def like_post(request): user=request.user if request.method=='POST': post_id=request.POST.get('post_id') post_obj= Post.objects.get(id=post_id)<--------------- Error highlighted in this line if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like,created=Like.objects.get_or_created(user=user,post_id=post_id) if not created: if like.value=='Like': like.value='Unlike' else: like.value='Like' like.save() return redirect('blog:post_list') Here is the template: <form action="{% url 'blog:like-post' %}" method="POST"> {% csrf_token %} <input type="hidden" name="post_id" value='{{obj.id}}'> {% if user not in obj.liked.all %} <button class="ui button positive" type="submit">Like</button> {% else %} <button class="ui button negative" type="submit">Unlike</button> {% endif %} <strong>{{ obj.like.all.count }} … -
Django - Add the same set of objects to a queryset using a ManyToMany field
I have pizzas and I have toppings. class Pizza(ModelBase): name = models.CharField(max_length=255) toppings = models.ManyToManyField('Topping', blank=True, related_name='pizzas') class Topping(ModelBase): name = models.CharField(max_length=255) Let's suppose I want to add the toppings Tomato and Cheese to every pizza in my database. At the moment I can do it with a nasty for loop: toppings = Toppings.objects.filter(Q(name='Tomato') | Q(name='Cheese')) for pizza in Pizza.objects.all(): pizza.toppings.add(*toppings) Is there a way to achieve the same thing without having to loop all the pizzas? Maybe using the through table that Django creates? I know that I can delete the toppings from all the pizzas using the following query: Pizza.toppings.through.objects.filter(topping__in=toppings).delete() but I haven't been able to add toppings to multiple pizzas without the for loop. -
Why is one text element of a table not aligning with the rest?
I'm making a game based off of a gameshow with Django, and want the users to be able to select a specific episode to play. The page in question is after the users have selected a year from the database, when they select the month from which they want to play. For some reason, no matter which year is selected, the month of March is always not aligned with the rest of the text. This occurs if March is the first, second, or third available month. I have not styled it differently from the others, and when I click inspect it randomly aligns with the rest (pictures attached). I've attached the code from episode_month.html and main.css. If anyone could help me align this month or give insight as to why it's above the others I'd appreciate it--it's been driving me crazy! episode_months.html: {% extends "game/base.html" %} {% load static %} {% block content %} <div class = "mode">Available Months</div> <div class = "mode_info">{{ year }}</div> <table class = "board"> {% for month_group in months %} <tr class = "row"> {% for month in month_group %} {% if month != "" %} <th class = "tile-months board_cat"> <a class = board_month … -
Cmd is not finding my files. I can see them in file explorer, but am unable to see them or access them in cmd
I am unable to access bookbuddy or activate my python virtualenv. The problem is not specific to this Project-BookBuddy directory. There are strange and inconsistent results in other directories as well. I recently synced with oneDrive. IDK if that has anything to do with this. -
Django + chart.js: plot with django Queryset data
I am across a problem that I cannot handle. I passing queryset data from a django view to its corresponding template and I want to use this data to plot a graph with chart.js I am trying to achieve this without using Ajax requests. However, when I try to acquire the queryset data with javascript to pass it in chart.js it renders an error. Here is what I have done in html: <div id="default_data"> <p> {{ default_items }} </p> </div> <div id="labels"> <p>{{ labels }} </p> <div class="col-lg-6"> <div id="tag3" class="card-footer small text-muted">{% trans 'ITEMS WITH HIGHEST NUMBER OF SALES (3 MONTHS)' %}</div> <div class="bar-chart block"> <canvas id="myChart3" height="90"></canvas> </div> </div> and here is what labels and default_data render: <QuerySet [58.0, 62.0, 74.0, 60.0, 16.0, 1.0, 1.0, 1.0, 1.0, 2.0]> <QuerySet ['372750', '372600', '372650', '372700', '372150', '289807', '289922', '289840', '289923', '372310']> and javascript: <script> var ctx3 = document.getElementById('myChart3').getContext('2d'); var labels = document.getElementById("labels"); var myChart3 = new Chart(ctx3, { type: 'bar', data: { labels: labels, datasets: [{ label:'références avec nombre de ventes élevé', data: default_data, label: '# of Votes', borderWidth: 1, }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); </script> I don't … -
paginate by a number of objects django
So pagination isn't working even without initiating django-filters from templates, I'm not able to paginate by the number of objects I want, it's showing all of them at once *Note: I'm not saying both should work together(pagination and django-filter), just that I wanna fix the pagination views.py def music_page(request): #pagination & filter music = Music.objects.all().order_by('-id') music_filter = MusicFilter(request.GET, queryset=music) paginator = Paginator(music, 6) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) try: music = paginator.page(page_number) except PageNotAnInteger: music = paginator.page(1) except EmptyPage: music.paginator.page(paginator.num_pages) return render(request, template_name='main/music.html', context={'music': music, 'page_obj': page_obj, 'filter': music_filter}) template <div class='card'> {% for m in filter.qs %} <div class='year'>{{m.Year}}</div> <div class='song_name'>{{m.song}}</div> {% endfor %} </div> -
What is the correct way to show multiple size HTML form fields for different resolutions
I have a Django form I am rendering manually, using the widget_tweaks django app, and bootstrap 4. Bootstrap has utilities to show or hide elements based on the resolution, and I thought this would be ideal to control how a contract form displays on desktop verse a mobile device. I included each form field twice, but failed to realize that even though it is not shown on the screen, it is still present and active. As such, my form was not being submitted, and worse the error that a form field needs to be filled in was also not visible. What is the correct way to resize form fields for different resolutions, or to deactivate form fields if they are not shown on screen? This was my attempt: <form method="POST">{% csrf_token %} <table class="table table-borderless"> <tr class="d-flex"> <td class="col-2 d-none d-sm-block"><b>Name</b></td> <td class="col-10 d-none d-sm-block">{% render_field form.name class+="form-control" placeholder="Your Name" %}</td> </tr> <!-- <tr class="d-flex d-sm-none"> <td class="col-4 d-sm-none"><b>Name</b></td> <td class="col-8 d-sm-none">{% render_field form.name class+="form-control" placeholder="Your Name" %}</td> </tr>--> <tr class="d-flex"> <td class="col-2 d-none d-sm-block"><b>E-mail</b></td> <td class="col-10 d-none d-sm-block">{% render_field form.email class+="form-control" placeholder="Your E-mail" %}</td> </tr> <!-- <tr class="d-flex d-sm-none"> <td class="col-4 d-sm-none"><b>E-mail</b></td> <td class="col-8 d-sm-none">{% render_field form.email class+="form-control" placeholder="Your … -
how to pivot with django pandas using foreign keys
I am using django-panda to make a dynamic table and I have achieved it, the problem I have is that I would like to add more rows to the table using foreign key relationships, in the documentation it says: "to span a relationship, just use the field name of related fields in models, separated by double underscores, "however this does not work with to_pivot_table. I did a test with to_dataframe and here the logic if it gives results, but what I need is to implement it in the pivot these are my models: class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True,related_name='student') quizzes = models.ManyToManyField(Quiz, through='TakenQuiz') interests = models.ManyToManyField(Subject, related_name='interested_students') def get_unanswered_questions(self, quiz): answered_questions = self.quiz_answers \ .filter(answer__question__quiz=quiz) \ .values_list('answer__question__pk', flat=True) questions = quiz.questions.exclude(pk__in=answered_questions).order_by('text') return questions def __str__(self): return self.user.username class TakenQuiz(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='taken_quizzes') quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='taken_quizzes',verbose_name='Examen') score = models.FloatField() date = models.DateTimeField(auto_now_add=True) objects = DataFrameManager() and my views class ResultadosTotales(ListView): def get(self,request,*args,**kwargs): examen=TakenQuiz.objects.all() qs=TakenQuiz.objects.all() df2=taken.to_dataframe(['student__user__first_name' ,'quiz', 'score'], index='student') print(df) #here I did the test with the related attribute and if it works rows = ['student','student__user__first_name'] #Here it does not work even though the documentation uses the same logic rows = ['student'] cols = ['quiz'] print(df2) pt … -
Django - saving an already created file to file.field()
My program essentially creates an excel file by integrating an api and webscraping It then puts that excel file into a folder. Then, I want to save that file to a Django model file field so that I can access it through the web portal. Can somebody help me find documentation that would help with this? Or perhaps just give me a general direction of how to approach this problem? Thank you! TLDR Step 1: CREATE EXCEL FILE Step 2: STORE EXCEL IN SEPARATE FOLDER Step 3 (where I’m stuck): SAVE THAT EXCEL FILE IN SAID SEPARATE FOLDER INTO A MODEL FILE FIELD. I’d greatly appreciate any help :) -
I've been trying to build a simple Django website but have been running into an error
I've been stuck with this DoesNotExist at /match/create Match matching query does not exist. error, and can not figure out what the problem is. Any help would be appreciated. This is my urls.py from django.conf.urls import url from django.urls import path, include from . import views app_name = 'match' urlpatterns = [ path('', views.match, name="list"), url('create/', views.profile_create, name="create"), path('<slug:slug>', views.match_detail, name="detail"), ] This is my views.py from django.shortcuts import render from .models import Match from django.http import HttpResponse def match(request): matches = Match.objects.all().order_by('date') return render(request, 'match/match.html', { 'matches': matches }) def match_detail(request, slug): #return HttpResponse(slug) match = Match.objects.get(slug=slug) return render(request, 'match/match_detail.html', { 'match': match }) def profile_create(request): return render(request, 'match/profile_create.html') This is my profile_create.html {% extends 'base_layout.html' %} {% block content %} <div class="create-match"> <h2>Create a Profile</h2> </div> {% endblock %} -
Best way to upload CSV and insert its info into database table using Django and PostgreSQL
What is the best way to upload a CSV file information and then saving it into a PostgreSQL table? If the upload is successful I will check on the database, I don't want to show the table anywhere in the templates. Please inform if you need more info. template where the upload will happen: {% extends "product_register/base.html" %} {% block content %} <form action="" method="post" autocomplete="off"> {% csrf_token %} <label for="file1">Upload a file: </label> <input type="file" id="file1" name="file"> <div class="row"> <div class="col-md-8"> <button type="submit" class="btn btn-success btn-block btn-lg"><i class="far fa-save"></i> Submit</button> </div> <div class="col-md-4"> <a href="{% url 'product_list' %}" class="btn btn-secondary btn-block btn-lg"> <i class="fas fa-stream"></i> Lista de Produtos </a> </div> </div> </form> {% endblock content %} views.py def category_form(request): """Cadastro de Categorias""" if request.method == "GET": return render(request, "product_register/category_form.html") else: #CSV UPLOAD HERE return render(request, "/product") models.py class Category(models.Model): """Classe Categoria""" name = models.CharField(max_length=20) def __str__(self): return self.name forms.py class CategoryUpload(forms.ModelForm): """Upload de Categorias""" class Meta: model = Category fields = "__all__" -
After upgrade, raw sql queries return json fields as strings on postgres
I am upgrading a Django app from 2.2.7 to 3.1.3. The app uses Postgres 12 & psycopg2 2.8.6. I followed the instructions and changed all my django.contrib.postgres.fields.JSONField references to django.db.models.JSONField, and made and ran the migrations. This produced no changes to my schema (which is good.) However, when I execute a raw query the data for those jsonb columns is returned as text, or converted to text, at some point. I don't see this issue when querying the models directly using Model.objects.get(...). import os, django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "big_old_project.settings") django.setup() with connection.cursor() as c: c.execute("select name, data from tbl where name=%s", ("rex",)) print(c.description) for row in c.fetchall(): for col in row: print(f"{type(col)} => {col!r}") (Column(name='name', type_code=1043), Column(name='data', type_code=3802)) <class 'str'> => 'rex' <class 'str'> => '{"toy": "bone"}' Trying the old trick of "registering" the adapter doesn't work, and shouldn't be needed anyway. import psycopg2.extras psycopg2.extras.register_json(oid=3802, array_oid=3807, globally=True) This app has a lot of history, so maybe something is stepping on psycopg2's toes? I can't find anything so far, and have commented out everything that seems tangentially related. Going through the release notes didn't help. I do use other postgres fields so I can't delete all references to contrib.postgres.fields from my models. Any … -
Can you use a Jinja variable within a python Tag?
I'm new to the Django Framework and I'm trying to create a link to a site in which I pass a variable that exists in the current loaded/rendered site as follows: {% extends "layout.html" %} {% block title %} {{ title }}{{ content_title }} {% endblock %} {% block body %} <h1>{{ title }}</h1> {{ content|safe }} {% if matches %} {% for item in matches %} <li><a href="{% url 'contentlist' item %}">{{ item }}</a></li> {% endfor %} {% endif %} {% if edit_button %} <form action="{% url 'edit' title %}" method="post"> <input type="Submit" value="Edit Entry"> </form> {% endif %} {% endblock %} Specifically this line keeps giving me an error: <form action="{% url 'edit' title %}" method="post"> I have also tried <form action="{% url 'edit' {{ title }} %}" method="post"> No matter what I try, I keep getting a NoReverseMatch exception with the following exception value Reverse for 'edit' with arguments '('',)' not found. 1 pattern(s) tried: ['edit/(?P[^/]+)$'] -
Endpoint with very slow response with DRF when receiving a parameter
I am using Django REST framework for my API and I start using filters, depending on the value, it make various count, but it take at least 3 minutes everytime I make a response. The serealizer use the context['request'] to get the url parameter and filter for the result class CheetosSerializer(serializers.ModelSerializer): total_cheetos = serializers.SerializerMethodField() cheetos_on_sale = serializers.SerializerMethodField() cheetos_on_stock = serializers.SerializerMethodField() class Meta: model = Cheetos fields = ( 'total_cheetos' ,'cheetos_on_sale' ,'cheetos_on_stock' ) read_only_fields = fields def get_total_cheetos(self,obj): request_object = self.context['request'] customer_id = request_object.query_params.get('Shop__id_Cat_Customer') if customer_id is None: return Cheetos.objects.filter(Estatus=3).count() else: return Cheetos.objects.filter(Estatus=3,Shop__id_Cat_Customer = customer_id).count() def get_cheetos_on_sale(self,obj): request_object = self.context['request'] customer_id = request_object.query_params.get('Shop__id_Cat_Customer') if customer_id is None: return Cheetos.objects.filter(Estatus=3, id_Cat = 1).count() else: return Cheetos.objects.filter(Estatus=3, id_Cat = 1,Shop__id_Cat_Customer = customer_id).count() def get_cheetos_on_stock(self,obj): request_object = self.context['request'] customer_id = request_object.query_params.get('Shop__id_Cat_Customer') if customer_id is None: return Cheetos.objects.filter(Estatus=3, id_Cat = 2).count() else: return Cheetos.objects.filter(Estatus=3, id_Cat = 2,Shop__id_Cat_Customer = customer_id).count() On the view is where I set the filterset parameter class CheetosView(DefaultViewSetMixin): filterset_fields = ['Shop__id_Cat_Customer'] queryset = Cheetos.objects.all() serializer_class = CheetosSerializer And I use postman to validate the data, and here it says the time it takes with the correct values I´m looking for: Postman Result Is there a way to make this much better? -
django: chart.js graph not rendering anything
I have been using chart.js for quite some time and I am coming across a bug that makes me bang my head off the wall for hours. I don't get any error outputed (neither in log, neither in server, neither in js from google dev tool) but nothing shows up on the graph. What's interesting is that although nothing at all gets rendered when there is a mistake in the chart.js code of one graph, in this case, everything else is rendered just fine. In addition, the data for this graph makes it from the view to the template just fine too. I can even print it on screen with no problem. I am out of things to try so here is my code: chart.js code: $(document).ready(function() { var endpoint = 'Supplier2.html' var default_items = [] var labels = [] var default_item1s = [] var label1s = [] ; $.ajax({ method: "GET", url: endpoint, success: function (data) { labels = data.labels default_items = data.default_items label1s = data.label1s default_item1s = data.default_item1s setChart() }, error: function (error_data) { console.log(error_data) } } ) function setChart(){ var ctx3 = document.getElementById('myChart3').getContext('2d'); var myChart3 = new Chart(ctx3, { type: 'bar', data: { labels: labels, datasets: [{ … -
Order objects that contain a many-to-many field that need to be ordered beforehand in Django
I've these two models: class Message(models.Model): content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) class Chat(models.Model): title = models.CharField(max_length=255) messages = models.ManyToManyField('Message') How do I order the chats by the last send message in each chat? -
No changes are detected when I try to make migrations while models.py was modified
I modified the model.py but when I tried to do the migrations the compliator answered me that there are none: >>>python manage.py makemigrations No changes detected My attempts to solve the problem: As you can see on the image I have a 'migrations' folder: python manage.py makemigrations -v 3 doesn't give me more informations In my main project folder, in settings.py there is the app: ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'todo' ] -
Django select_related doesn't show all fields, but raw SQL does
I have a table of hosts, and a table of parameters, with a foreign key linking the parameters back to hosts. I want to select all the hosts, and the parameter "kernelversion". >>> q = Parameter.objects.filter(name__exact='kernelrelease').select_related('host')[:1] This is the SQL query it shows will use, notice it's selecting all the fields from inventory_host, however only inventory_parameter columns are shown in the final QuerySet >>> print(q.query) SELECT `inventory_parameter`.`id`, `inventory_parameter`.`name`, `inventory_parameter`.`value`, `inventory_parameter`.`host_id`, `inventory_host`.`id`, `inventory_host`.`certname`, `inventory_host`.`report_timestamp`, `inventory_host`.`role`, `inventory_host`.`ipaddress`, `inventory_host`.`operatingsystemrelease`, `inventory_host`.`manufacturer`, `inventory_host`.`productname`, `inventory_host`.`alive`, `inventory_host`.`datacenter_id` FROM `inventory_parameter` INNER JOIN `inventory_host` ON (`inventory_parameter`.`host_id` = `inventory_host`.`id`) WHERE `inventory_parameter`.`name` = kernelrelease ORDER BY `inventory_parameter`.`name` ASC LIMIT 1 >>> q.values() <QuerySet [{'id': 133376, 'name': 'kernelrelease', 'value': '2.6.32-754.3.5.el6.x86_64', 'host_id': 4061}]> I tried to run the SQL query above manually, and it provides all the results it should. Why is django removing all the inventory_host columns from the output? MariaDB [opstools]> SELECT `inventory_parameter`.`id`, `inventory_parameter`.`name`, `inventory_parameter`.`value`, `inventory_parameter`.`host_id`, `inventory_host`.`id`, `inventory_host`.`certname`, `inventory_host`.`report_timestamp`, `inventory_host`.`role`, `inventory_host`.`ipaddress`, `inventory_host`.`operatingsystemrelease`, `inventory_host`.`manufacturer`, `inventory_host`.`productname`, `inventory_host`.`alive`, `inventory_host`.`datacenter_id` FROM `inventory_parameter` INNER JOIN `inventory_host` ON (`inventory_parameter`.`host_id` = `inventory_host`.`id`) WHERE `inventory_parameter`.`name` = 'kernelrelease' AND host_id = 4061 ORDER BY `inventory_parameter`.`name` ASC LIMIT 1\G *************************** 1. row *************************** id: 133376 name: kernelrelease value: 2.6.32-754.3.5.el6.x86_64 host_id: 4061 id: 4061 certname: myhost001.sub.domain.com report_timestamp: 2020-10-09 11:12:33.765000 role: qwerty ipaddress: … -
"Sent non-empty 'Sec-WebSocket-Protocol' header but no response was received" Django Channels
I get this error only in chrome (not in safari and not in firefox) when trying to connect to the server via a websocket: Sent non-empty 'Sec-WebSocket-Protocol' header but no response was received. The server accepts the connection but chrome unexpectedly closes it immediately. This is how I create a websocket connection on the frontend: const websocket = new WebSocket('ws://127.0.0.1:8000/ws/', ['Token', 'user_secret_token']) This is how my consumers.py looks: class MyConsumer(JsonWebsocketConsumer): def connect(self): self.room_group_name = 'example_room' # Join room group async_to_sync(self.channel_layer.group_add)(self.room_group_name, self.channel_name) self.accept() -
How do you list all warning filters in Python?
I just spent the day trying to remove this warning from my output: sys:1: ResourceWarning: unclosed file <_io.TextIOWrapper name='/dev/null' mode='w' encoding='UTF-8'> I just finished a binary search of about 100k lines of code to try to figure this out. I still haven't found what's leaving /dev/null open, but I did find that some of our code says: warnings.simplefilter("always") Removing that removes the warning. Hooray! I plan to remove that bit of code, but I'm curious of two things: Could I have avoided doing a binary search for this somehow? Enabling TRACEMALLOC=1 was entirely ineffective (maybe because this is in third-party code we import?) Once I remove this, is there a way to list all of the warning filters that are applied at a particular point in the code? Seems like an important thing to be able to analyze, but I can't figure out how.