Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dynamic type annotation for Django model managers custom method
I need help with type hint for a custom model manager method. This is my custom manager and a base model. I inherit this base model to other models so that I don't have to write common fields again and again. class BaseManager(models.Manager): def get_or_none(self, *args, **kwargs): try: return self.get(*args, **kwargs) except self.model.DoesNotExist: return None class BaseModel(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, verbose_name="ID", editable=False ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = BaseManager() # Set the custom manager class Meta: abstract = True This is an example model: class MyModel(BaseModel): category = models.CharField(max_length=10) Now for this: my_object = MyModel.objects.get_or_none( category="...", ) The type annotation is like this when I hover in my IDE: my_object: BaseModel | None = MyModel.objects. get_or_none(... But I want the type annotation like this: my_object: MyModel | None = MyModel.objects. get_or_none(... How can I do that? This works for the default methods like get and filter. But how to do this for custom methods like get_or_none? Please help me. Thanks -
Django unit tests suddenly stopped working
My unit tests were working fine, but for the past two days, they have been failing without any apparent reason. No new code additions or major changes have been made, yet they are failing. The same logic is working in other test cases, but for five specific tests, it has started to fail. I tried running the tests by checking out a previous branch where the tests were working fine, but now they have stopped working even under those conditions. I am completely clueless about what to do next. Below is the snippet which was implemented by sr dev, but he left the company two weeks ago. I don’t know this might not be filtering the data or there might be a scenario of overlapping of date for the data that we want to filter. Kindly help. class EntityBestDataSourceChange(models.Model): scope = models.TextField() scope_category = models.TextField() entity_id = models.IntegerField() child_id = models.IntegerField() year = models.IntegerField() source = models.TextField() operation = models.TextField() class Meta: unique_together = [ 'scope', 'scope_category', 'entity_id', 'child_id', 'year', 'source', 'operation'] @classmethod @transaction.atomic def perform_recalculate(cls): ebds_changes = ( EntityBestDataSourceChange.objects .select_for_update(skip_locked=True) .all() ) number_of_changes = len(ebds_changes) additions = set() removals = set() for ch in ebds_changes: key = ( ch.scope, … -
Process the image on the website using Pilgram
I'm completely zero in programming and I'm just trying to take the first steps. I think the solution to my problem is pretty simple, but I can't find it. I want to have 2 fields in the Images model: image and processed_image. I am using Django 5.1.4, Python 3.13.1, Pillow 11.1.0 and Pilgram 1.2.1 I want the user to upload an image to a form on the website. The image was processed using pilgram. And then the processed image was saved in the processed_image field. But when I save the picture, the processed_image field in the database remains empty. Please tell me what my mistake is? postcard/images/models.py from django.db import models from PIL import Image import pilgram import os from django.urls import reverse from django.contrib.auth.models import User from .services.utils import unique_slugify class Images(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user') title = models.CharField('Название', max_length=255) slug = models.SlugField("URL", max_length=255, unique=True, db_index=True) image = models.ImageField('Изображение', upload_to="images/%Y/%m/%d/") processed_image = models.ImageField('Отработанное изображение', upload_to="processed/%Y/%m/%d/", blank=True, null=True) time_create = models.DateTimeField('Дата создания', auto_now_add="True") def __str__(self): return self.title def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.image: self.process_image() def process_image(self): img_path = self.image.path img = Image.open(img_path) img = pilgram._1977(img) processed_path = os.path.join(os.path.dirname(img_path),f"processed_{os.path.basename(img_path)}") img.save(processed_path) self.processed_image = processed_path super().save(update_fields=['processed_image']) class Meta: verbose_name = … -
In the Wagtail admin panel, the person's image is not showing on the blog edit page
I have used a person as an author on the blog page, but when I open the blog edit page, I can only see the text, not the person's image. How can I display the image as well? -
Not able to connect to PostgreSQL database in Linux Fedora via VS Code terminal
So I'm using Linux Fedora. I'm in my current Django project directory. When I dual booted, I did save my postgresql application and saved my database backup with pg_dump onto my removable drive before I booted to Linux. I'm in VS Code, I installed all of the necessary packages/dependencies for my Django project. But before I can run Django server, I have to migrate my models to my db. The problem, is that I'm not able to connect to my postgresql db and I need to do this before I run python manage.py migrate running python manage.py makemigrations CMD works fine. So I'm new to Linux and I just need some help connecting to my db so that I can get my server running. Please keep in mind I'm using Fedora. I was able to install postgresql for Fedora with the following command sudo dnf install postgresql-server postgresql-contribsudo dnf install postgresql-server postgresql-contrib Here is the error I get in the console Is the server running on that host and accepting TCP/IP connections? connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections?` To be clear, I already have … -
Django frontend detect if user is logged in
I use django at backend and html/javascript for frontend. I am looking for a way to know in frontend if the user is logged in. If user is not logged in, upon pressing some buttons, the website shows a login overlay form. By just checking whether sessionid exists in the cookies or not you can find it out. But, the problem is SESSION_COOKIE_HTTPONLY in django settings is True and I do not want to turn it off. Thus, the document.cookies does not include the sesstionid due to security reason. Is there still any way to find the user is logged in without contacting the backend? -
Django queryset with annotate, order_by and distinct raises error when values is called
Can somebody explain to me why the following call works fine Order.objects.filter(part_description__icontains=search_query) .annotate(part_description_lower=Lower('part_description')) .order_by("part_description_lower", '-pk') But the following raises the error Cannot resolve keyword 'part_description_lower' into field Order.objects.filter(part_description__icontains=search_query) .annotate(part_description_lower=Lower('part_description')) .order_by("part_description_lower", '-pk') .values('pk') Thank you in advance. -
How to access submitted form request data in Django
I want value of submitted data in init . I can get data after form.valid() through cleaned_data but can't access those data in init after submitting form form.py class MyForm(forms.Form): def __init__(self, *args, **kwargs): // Want to access submitted source and medium data here super(MyForm, self).__init__(*args, **kwargs) // or Want to access submitted source and medium data here view.py I am getting two different value source and medium in request.GET myform = MyForm(request.GET) -
Why doesn't the Python TimedRotatingFileHandler rollover, if there are Celery jobs running?
Python 3.12.3, Celery 5.3.6, Django 4.2.11, Ubuntu 22.04.4 I have an infrastructure of Django and Celery servers running simultaneously on an Ubuntu server. For logging I use DiscordHandler and customized TimedRotatingFileHandler defined as so: class CustomizedTimedRotatingFileHandler(TimedRotatingFileHandler): ''' log_name.date.log.log -> log_name.date.log ''' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.namer = lambda name: name.replace(".log", "") + ".log" The project logging is configured in the settings file: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { **{ f"{k}_file": { "level": "INFO", "class": "api.logging.CustomizedTimedRotatingFileHandler", "filename": "log/sync.log", "when": "midnight", "backupCount": 2, "formatter": v, } for k, v in {"django": "verbose", "celery": "celery"}.items() } }, 'loggers': { 'django': { 'handlers': ['django_file'], 'level': 'INFO', 'propagate': True, }, 'django.server': { 'handlers': ['django_file'], 'level': 'INFO', 'propagate': False, }, 'celery': { 'handlers': ['celery_file'], 'level': 'INFO', 'propagate': False, } } } Right now I have 2 log files and then a file of today (which gets logs in only from Django, not Celery). I've looked through the discord logs and have seen that there were some celery jobs working at midnight. And this is not the first occurrence, in fact, all the times the case has been that in the midnight there were ongoing tasks, which interrupted the rollover. How do … -
socialaccount + mfa: how to bypass the mfa code form?
on an older version of django-allauth (0.61.1) I used totp for the two-auth. Now I've udpdated to django-allauth[mfa]==65.3.0 and I have an issue by using the socialaccount auth. Before I used a customer AccountAdapter to check if the user coming from a microsoft: class AccountAdapter(DefaultAccountAdapter): def has_2fa_enabled(self, user): """Returns True if the user has 2FA configured.""" return user.has_2fa_enabled if user.is_authenticated else False def login(self, request, user): # Require two-factor authentication if it has been configured. if ( self.has_2fa_enabled(user) and not request.path == "/auth/microsoft/login/callback/" ): redirect_url = reverse("two-factor-authenticate") # Add GET parameters to the URL if they exist. if request.GET: redirect_url += "?" + urlencode(request.GET) raise ImmediateHttpResponse(response=HttpResponseRedirect(redirect_url)) return super().login(request, user) Now, with the new update, the 2FA code is asked AFTER the super().login How can I bypass the MFA code? I've checked the documentation and I see only "is_mfa_enabled" in the DefaultMFAAdapter but this is not nice as it will just say False on is_mfa_enabled but not only change if the app asks the code or not. Is there any other way for that? -
Why is my @import in CSS not working when importing other CSS files?
I'm building a Django project and trying to organize my CSS files by importing them into a single index.css. However, the styles from the imported files are not being applied when I include only index.css in my base.html. Here's what I've done: File Structure: static/ ├── css/ │ ├── index.css │ ├── footer.css │ └── courses/ │ └── courses.css index.css: @import url("footer.css"); @import url("courses/courses.css"); .verticalSpace { padding-top: 100px; } base.html: <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="{% static 'css/index.css' %}"> </head> <body> {% block content %} {% endblock %} </body> </html> Observations: If I directly include footer.css or courses/courses.css in the HTML, the styles work. <link rel="stylesheet" href="{% static 'css/courses/courses.css' %}"> The styles do not work when I rely on @import in index.css. Questions: Why are the imported styles not applying when using @import in index.css? Is there a better way to structure CSS imports in Django to only link index.css in the HTML? Could this issue be related to Django's STATIC_URL or how @import resolves paths? What I've Tried: Checked that static files are correctly set up in settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [BASE_DIR / 'static'] Verified that the CSS files load correctly when linked directly. Tried … -
Circular import in Django
Im getting this error : does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import whenever i try python manage.py runserver app urls.py from django.urls import path from . import views urlpatterns = [ path ('', views.index, name='index'), ] project urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')), ] app Views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse('<h1> Hello man</h1>') Im using Django 4.1, and Python 3.10.10, I also tried this with python 3.12 and Django 5.1.4, still error persisted. Without this particular line of code below in the parent app, the program runs fine. path('', include('myapp.urls')), but when I include the above line of code I get the following error: "does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import." I tried changing python environments, directories, rewriting the code and trying out in different python and django versions … -
Issues Importing CSV Data in Django Custom Management Command (DictReader Parsing Error)
Hi everyone, I'm working on a Django project where I need to import questions from a CSV file into my database using a custom management command. However, I'm facing an issue with parsing the CSV rows. Here’s what I’m doing: I’m using csv.DictReader to read the CSV file. My CSV file includes columns like subject, topic, difficulty_level, text, options, correct_option, and image. Here’s a sample of my CSV: subject,topic,difficulty_level,text,options,correct_option,image Physics,Thermodynamics,2,"Calculate ( W = P \cdot \Delta V ) for ( P = 100 , kPa ).","{""A"":""100 J"",""B"":""200 J"",""C"":""300 J"",""D"":""400 J""}","A","question_images/thermo_diagram.png" Math,Calculus,3,"Evaluate ( \int_0^1 x^2 dx ).","{""A"":""1/2"",""B"":""1/3"",""C"":""1/4"",""D"":""1/5""}","B","" Here’s the issue I’m encountering: When I run my management command, DictReader doesn’t seem to parse the rows correctly. I get errors like: javascript Copy code Error importing question: Unknown - 'subject' Debugging shows that the entire row is being read as a single key-value pair, rather than splitting into individual fields. I’ve tried: Ensuring the CSV file is UTF-8 encoded. Adding debugging to confirm the raw content of the CSV. Here’s my current code snippet for reading the CSV: python Copy code with open(csv_file, newline='', encoding='utf-8-sig') as file: reader = csv.DictReader(file) for row in reader: print("Parsed Row:", row) # Debugging What could be … -
how to render the content in the wagtail page especially listblock content
this my model file in which i define cards to the wagtail admin from wagtail.models import Page from wagtail.fields import StreamField from wagtail.admin.panels import FieldPanel from strems import Blocks class TestPage(Page): """Page for testing card block rendering.""" template = "strems/test.html" cards = StreamField( [("cards", Blocks.cardblocks())], blank=True, null=True, ) content_panels = Page.content_panels + [ FieldPanel("cards"), ] class Meta: verbose_name = "Test Page" verbose_name_plural = "Test Pages" this is my block.py in which i specify my list block in the strems app class cardblocks(StructBlock): title =CharBlock(required=True,help_text="Add text here") cards=ListBlock( StructBlock( [ ("image", ImageChooserBlock(require=True)), ("title",CharBlock(required=True,max_length=23)), ("text",TextBlock(required=True,max_length=50)), ("button_page",PageChooserBlock(required=False)), ("button_url",URLBlock(required=False)), ], ) ) template = "strems/card_block.html" class Meta: icon = "placeholder" label = "blockcards" ad also this is my html template for render the content {% extends "base.html" %} {% load wagtailcore_tags %} {% load wagtailimages_tags%} {% block content %} <div class="container"> <div class="container"> <h1>{{ self.title }}</h1> <div class="row"> {% for card in self.cards %} <div class="card col-md-4" style="width: 18rem; margin: 10px;"> {% if card.image %} <img src="{{ card.image.url }}" class="card-img-top"> {% endif %} <div class="card-body"> <h5 class="card-title">{{ card.title }}</h5> <p class="card-text">{{ card.text }}</p> {% if card.button_page %} <a href="{{ card.button_page.url }}" class="btn btn-primary">Go to {{ card.button_page.title }}</a> {% elif card.button_url %} <a href="{{ card.button_url … -
"Right" way to define helper functions for Django models' Meta classes
I'm trying to simplify a very verbose and repetitive Check constraint for a model, whose logic is currently very hard to parse, factoring out and aptly renaming the repetitive parts. Basically I want to turn this (simplified and abstracted snippet): class MyModel(models.Model): class Meta: constraints = [ models.CheckConstraint( check = ( ( models.Q(foo = True) & ( ( models.Q(field1 = 'X') & models.Q(field2 = 'Y') & models.Q(field3 = 'Z') ) | ( models.Q(field4 = 1) & models.Q(field5 = 2) & models.Q(field6 = 3) ) ) ) | ( models.Q(foo = False) & ( ( models.Q(field1 = 'X') & models.Q(field2 = 'Y') & models.Q(field3 = 'Z') ) | ( models.Q(field4 = 4) & models.Q(field5 = 5) & models.Q(field6 = 6) ) ) ) ), name = 'foo', ), ] Into this: class MyModel(models.Model): class Meta: constraints = [ models.CheckConstraint( check = ( ( models.Q(foo = True) & ( condition1 | condition2 ) ) | ( models.Q(foo = False) & ( condition1 | condition3 ) ) ), name = 'foo', ), ] What I've tried / thought of trying: Factoring out the conditions, both as attributes and methods in Meta itself; that didn't work: TypeError: 'class Meta' got invalid attribute(s): condition1,condition2,condition3; Factoring … -
How to display multiple lines of text in django admin for Headers?
Similar questions that have already been asked are for data fields like in Here and Here But how to split the header in multiple lines? Considering a Django app with model and admin setup like this: models.py from django.db import models class TaskItem(models.Model): group = models.ForeignKey(TaskGroup, on_delete=models.CASCADE) title = models.CharField(max_length=32, null=False, blank=False) description = models.CharField(max_length=45, null=False, blank=False) reward = models.IntegerField(default=1000, null=False, blank=False) admin.py class TaskItemAdmin(admin.ModelAdmin): list_display=['title', 'group', 'reward'] list_filter=('group',) How can I rename headers to Task Title, Task Group and Task Reward with line breaks? -
How to update a list of To-Do items with checkboxes and save changes using React and Django?
I am trying to update a list of To-Do items using React for the frontend and Django for the backend. Each item has a checkbox to mark it as complete or incomplete. When I click the "Save" button, I want the updated data to be sent to the backend via a PUT request. However, I am facing issues with updating the items properly. Here’s my React handleSave function that triggers the PUT request: const handleSave = async (e) => { e.preventDefault(); console.log('handleSave called'); const updatedItems = items.map((item) => { const checkbox = e.target[`c${item.id}`]; console.log(`Processing item id ${item.id}, checkbox value:`, checkbox?.checked); return { id: item.id, todolist: 1, text: item.text, complete: checkbox ? checkbox.checked : false, duration: item.duration, }; }); try { console.log('Payload to send:', updatedItems); const response = await axios.put( `${import.meta.env.VITE_API_URL}/todo-items/1`, // Update the endpoint if needed updatedItems, { headers: { 'Content-Type': 'application/json' }, // Set proper headers } ); console.log('Items updated successfully:', response.data); } catch (error) { console.error('Error updating items:', error.message, error.response?.data); } }; Here’s the Django view handling the request: @api_view(['GET', 'PUT']) def todo_items(request, id): try: ls = ToDoList.objects.get(id=id) except ToDoList.DoesNotExist: return Response({"error": "List not found"}, status=404) if request.method == 'GET': incomplete_items = ls.item_set.filter(complete=False) complete_items = ls.item_set.filter(complete=True) items = … -
Frontend React(next.js) Backend (DJango) and Database (PostGreSQL)
I am working on a small project with this stack Frontend React(next.js) ==> Backend (Django) ==> Database (PostgreSQL). Please advise if this is ok. donor management system (dms) Thanks & Regards Nawaz Mohammed -
Annotate multiple values as JSONObject - parse datetime
I'm annotating my QuerySet as follows, using JSONObject, to obtain multiple fields from Scan: MyModel.objects.annotate( myscan=Subquery( Scan.objects .all() .values(data=JSONObject( id='id', nin='nin', datetime='datetime') )[:1] ) ) I want to get a proper datetime representation though, somehow. When I try to use myscan.datetime, I get the string representation (e.g. datetime': '2024-12-31T09:19:30.221953+00:00. How can I either return the datetime object itself (instead of a string; assuming this is impossible when using JSONObject) or alternatively do a strptime() before returning the string as part of the JSON? Obviously I could parse the string, convert to datetime and then do strptime() again, but that seems like a dirty solution. Any suggestions? -
Django - javascript - ajax does not work with javascript created lines
I have three classes lets say, class Item(models.Model): id = models.AutoField(primary_key=True) # Explicitly define the id column as the primary key itemref = models.IntegerField(blank=True, null=True) code = models.CharField(max_length=150, db_collation='Turkish_CI_AS', blank=True, null=True) tanimlama = models.CharField(max_length=150, db_collation='Turkish_CI_AS', blank=True, null=True) itemname = models.CharField(max_length=150, db_collation='Turkish_CI_AS', blank=True, null=True) class SAFiche(models.Model): nothing important class SALine(models.Model): safiche = models.ForeignKey(SAFiche, on_delete=models.CASCADE) item = models.ForeignKey('accounting.Item', on_delete=models.CASCADE) In views, I have ajax for autocomplate: def item_autocomplete(request): query = request.GET.get('q', '') items = Item.objects.filter( Q(code__icontains=query) | Q(itemname__icontains=query) | Q(tanimlama__icontains=query) )[:10] # Limit to 10 results results = [] for item in items: label = f"{item.code or ''} - {item.itemname or item.tanimlama or ''}" results.append({ 'id': item.id, 'label': label.strip(' -'), }) return JsonResponse(results, safe=False) I properly adjusted rest. This is my forms: class SALineCreateForm(forms.ModelForm): urun_search = forms.CharField( label="Ürün Ara", required=False, widget=forms.TextInput(attrs={ 'placeholder': 'Ürün kodu veya adı...', 'class': 'item-search-input border rounded p-2 w-full', 'autocomplete': 'off' }) ) class Meta: model = SALine fields = [ 'urun', 'miktar' ] widgets = { 'urun': forms.HiddenInput(), 'miktar': forms.NumberInput(attrs={'class': 'w-full form-input rounded-md'}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # If editing an existing line, fill the search box with the item name if getattr(self.instance, 'urun_id', None): self.fields['urun_search'].initial = str(self.instance.urun) SALineCreateFormSet = inlineformset_factory( SAFiche, SALine, form=SALineCreateForm, extra=1, … -
React, Django. Gunicorn, nginx , docker setup for production ready and not ablet to server static files for both frontend and backend
This is the current project director for my project as of now Project/ │── .env ├── docker-compose.yml # Docker Compose configuration file │ ├── Frontend/ # React Frontend (Client-side) │ ├── Dockerfile # Dockerfile for React app build │ ├── package.json # React package file │ ├── public/ # Public assets for React │ ├── src/ # React source code │ ├── build/ # React build output (this is where `npm run build` │ ├── nginx.conf └── Backend/ # Django Backend (Server-side) ├── Dockerfile # Dockerfile for Django app build ├── manage.py # Django manage.py file ├── Backend/ # Django application code (models, views, etc.) ├── requirements.txt ├── static/ # Static files (collected by `collectstatic`) ├── media/ # Media files (user-uploaded files) └── .dockerignore # Docker ignore file i have this directory structure where i have 2 folders for backend and front end each is build with Django and react respectively and i have the nginx file in the frontend directory to copy the first build in the frontend container but the thing is that i also share the same volume with the django also but nginx is not ablet to server sttic files to django as well get 404 … -
Django Vercel Deployment Issue | 500: INTERNAL_SERVER_ERROR | ModuleNotFoundError: No module named 'distutils'
I have been trying to deploy a Django App on vercel, it is getting deployed but the website is not working says "This Serverless Function has crashed" Requirements.txt Django==3.1.12 djongo==1.3.7 dnspython==2.7.0 pymongo==3.11.4 psycopg2-binary~=2.9.6 setuptools==75.7.0 vercel.json { "builds": [{ "src": "inventory_management/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.9" } }], "routes": [ { "src": "/(.*)", "dest": "inventory_management/wsgi.py" } ] } The error says, from distutils.version import LooseVersion ModuleNotFoundError: No module named 'distutils' Tried adding setuptools in requirements.txt but still the same issue -
social_core.exceptions.MissingBackend: Missing backend "google-oauth2" entry in Django with Google OAuth2
I'm working on integrating Google OAuth2 in my Django REST Framework project using django-rest-framework and social-django. However, when I try to authenticate using the endpoint: GET /api/o/google-oauth2/?redirect_uri=http://localhost:3000/auth/google I get the following error: social_core.exceptions.MissingBackend: Missing backend "google-oauth2" entry What could be causing the Missing backend "google-oauth2" entry error? Am I missing any configuration, or could there be an issue with the library versions? Any help or guidance would be appreciated. Added the following to my settings.py: AUTHENTICAION_BACKEN,DS =[ 'django.contrib.auth.backends.ModelBackend', 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.facebook.FacebookOAuth2', ] SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'openid', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', ] The redirect_uri (http://localhost:3000/auth/google) matches the one registered in the Google API Console. -
Django annotation from different sources
I'm trying to build following annotation, essentially looking up the nin field from a person either from the IDcard or from the Person model. .annotate( checkins_scan=Scan.objects.filter(models.Q(nin=OuterRef("person__idcard__nin") | models.Q(national_number=OuterRef("person__nin"))) .values( data=JSONObject(id="id", nin="nin", datetime="datetime") )[:1] ) However, I get following error: NotImplementedError: Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations. Looks like I'll need bitor(), but I'm not getting any further with the basic examples I'm finding (e.g. documentation here). When I try to work with F() I get TypeError: F.__init__() got an unexpected keyword argument 'nin'. Any clues on how to properly do this? -
VSCode Test Explorer hangs despite no errors in the output & all tests being collected (in the output)
I have been having a lot of issues with Test Explorer in VSCode. It has been working fine up until last week. I was writing new tests and clicked "Refresh Tests" and then it suddenly (and pretty randomly) stopped working - specifically it "discovers" tests forever. And that is despite the fact that the output shows that the tests seem to be discovered correctly in the output window: The tests are also all passing if I run them with standard pytest terminal command: My directory structure is as follows: application ├── backend │ ├── src | ├── |── __init__.py | ├── |── manage.py | ├── |── app1 | ├── |── ├── __init__.py | ├── |── ├── folder1 | ├── ├── ├── ├── __init__.py | ├── |── ├── ├── views.py | ├── |── ├── ├── class1.py | ├── |── ├── ├── class2.py | ├── ├── ├── ├── tests | ├── ├── ├── ├── ├── __init__.py | ├── ├── ├── ├── ├── test_class1.py | ├── ├── ├── ├── ├── test_class2.py | ├── ├── ├── ├── ├── test_views.py | ├── |── ├── folder2 | ├── ├── ├── ├── __init__.py | ├── |── ├── ├── views.py | ├── |── ├── ├── class1.py | ├── …