Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
csrf_token verification failed?
I am a beginner and searched a lot about it but do not got any thing please explain why this error is coming. I have used this code from here: JavaScript post request like a form submit Error is coming from the following code in my html template in under script tag: This code is from Davidson Lima comment: post("{% url 'savep' %}", {name: user_name, pass: user_pass, csrfmiddlewaretoken: $("csrf_token").val()}); Here is the code of views.py def save_login(request): x = request.POST['user'] y = request.POST['pass'] member = credentials(user_name=x, user_pass=y) member.save() Error: Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token from POST has incorrect length. -
Django foreignkey between two databases
I'm looking to connect two SQLite tables together (oh dear). I found this solution : How to use django models with foreign keys in different DBs? , I adapted it to my models and my code (I think). I have no bad answers from django. However, I would like to modify the entry with the admin view of django, and when I try to add the entry with the foreign key of another database, I get this answer: Exception Type: OperationalError at /admin/users/character/add/ Exception Value: no such table: books How to adapt to fix it? models database default from django.db import models from users.related import SpanningForeignKey from books.models import Books class Character(models.Model): last_name = models.fields.CharField(max_length=100) first_name = models.fields.CharField(max_length=100) book = SpanningForeignKey('books.Books', null=True, on_delete=models.SET_NULL) def __str__(self): return f'{self.first_name} {self.last_name}' models external database from django.db import models # Create your models here. class Books(models.Model): title = models.TextField() sort = models.TextField(blank=True, null=True) timestamp = models.TextField(blank=True, null=True) # This field type is a guess. pubdate = models.TextField(blank=True, null=True) # This field type is a guess. series_index = models.FloatField() author_sort = models.TextField(blank=True, null=True) isbn = models.TextField(blank=True, null=True) lccn = models.TextField(blank=True, null=True) path = models.TextField() flags = models.IntegerField() uuid = models.TextField(blank=True, null=True) has_cover = models.BooleanField(blank=True, null=True) … -
Django REST API: Invalid data. Expected a dictionary, but got User
I want to design a REST API where user can submit a new car record using POST request. The user is automatically should be set as creator. Under my models.py I have: class CarRecord(models.Model): type = models.CharField(max_length=50) license = models.CharField(max_length=50) creator = models.ForeignKey(User,on_delete=models.DO_NOTHING) Under my serializers.py I have: class UserSerializer(serializers.ModelSerializer): username = serializers.CharField(max_length=50) class Meta: model = User fields = ['username'] class CarRecordSerializer(serializers.ModelSerializer): type = serializers.CharField(max_length=50) license = serializers.CharField(max_length=50) creator = UserSerializer() class Meta: model = CarRecord fields = ('__all__') And In the post method I have: class CarRecordViews(APIView): def post(self, request): user = request.user if not user.is_authenticated: user = authenticate(username=request.data['username'], password=request.data['password']) if user is None: return Response(data={"error": "bad username/password"}, status=status.HTTP_401_UNAUTHORIZED) data = { 'type': request.data['type'], 'license': request.data['license'], 'creator': user } serializer = CarRecordSerializer(data=data) serializer.is_valid(raise_exception=True) return Response({"message": "success"}, status=status.HTTP_201_CREATED) But I get: { "creator": { "non_field_errors": [ "Invalid data. Expected a dictionary, but got User." ] } } I want to keep the user as the creator. I'm not sure I fully understand how serializers work but I believe the problem is in that file. Have can I make it work? -
Get Dn from an AD, using LDAP protocol on python without connection
I try ot make a Django app using connection by ldap. To test the connection you need to use <ldapInstance>.simple_bind_s(User, Password) where User is a DN : CN=me,OU=other,DC=com (for exemple) So i try to get this DN by a function using : <ldapInstance>.search_s(paramers...) and return this error : info: 0002020: Operation unavailable without authentification The problem is, if i want DN, i need connection using DN for connection. Someone have an idea ? -
Django Upload File, Analyise Conents and write to DB or update form
I'm pretty new to Django, Trying to get my grips with it, and expand what I think its capable of doing, and maybe one of you more intelligent people here can point me in the right direction. I'm basically trying to build a system similar to a so called "Asset Management" system, to track software version of a product, so when an engineer updates the software version, they run a script which gathers all the information (Version, Install date, Hardware etc), which is stored in a .txt file, The engineer then comes back to the website and upload this .txt file for that customer, and it automatically updates the fields in the form, or directly to the database. While, I've search a bit on here for concepts, I haven't been able to find something similar (Maybe my search terms aren't correct?), and wanted to ask if anyone knows, what I'm doing is even feasible, or am I lost down the rabbit hole of limitations :) Maybe its not do-able within Django, Any suggestions on how I should approach such a problem would be greatly appreciated. -
how can I count data from foreign key field in Django template?
models.py: class Region(models.Model): city = models.CharField(max_length=64) class Properties(models.Model): title = models.CharField(max_length=200) Region = models.ForeignKey(Region, related_name='Region', on_delete=models.Cascade) how can i count all properties which have the same region ? -
Django import-export library ForeignKey error (IntegrityError: FOREIGN KEY constraint failed in django)
First of all please sorry for my English. )) So I have a problem with Django import-export library when I try to import data from csv/xls/xlsx files to the Django application DB. How it looks like. Here is my models.py: class Department(models.Model): department_name = models.CharField(max_length = 50, default = '', verbose_name = 'Подразделение') def __str__(self): return f'{self.department_name}' class ITHardware(models.Model): it_hardware_model = models.CharField(max_length = 100) it_hardware_serial_number = models.CharField(max_length = 100, blank = True, default = '') it_hardware_department = models.ForeignKey(Department, related_name = 'department', on_delete = models.SET_NULL, default = '', null = True, blank = True, db_constraint=False) admin.py: @admin.register(Department) class DepartmentAdmin(admin.ModelAdmin): list_display = ('department_name', ) actions = [dublicate_object] @admin.register(ITHardwareManufacturer) class ITHardwareManufacturerAdmin(admin.ModelAdmin): list_display = ('manufacturer', ) actions = [dublicate_object] class ITHardwareImportExportAdmin(ImportExportModelAdmin): resource_class = ITHardwareResource list_display = ['id', 'it_hardware_manufacturer', 'it_hardware_model', 'it_hardware_serial_number', 'it_hardware_department'] actions = [dublicate_object] resource.py: class ITHardwareResource(resources.ModelResource): it_hardware_department = fields.Field( column_name = 'it_hardware_department', attribute = 'ITHardware.it_hardware_department', widget = widgets.ForeignKeyWidget(Department, field = 'department_name')) class Meta(): model = ITHardware fields = ( 'id', 'it_hardware_model', 'it_hardware_serial_number', 'it_hardware_department', ) export_order = ( 'id', 'it_hardware_model', 'it_hardware_serial_number', 'it_hardware_department', ) import file: import file If I try to import data from file, I get such error: String number: 1 - ITHardwareManufacturer matching query does not exist. None, Canon, BX500CI, 5B1837T00976, Office_1, … -
How to display multiple django database models in a flex box row?
So just to give some information, I know how flexbox works and sorta know how django works and have displayed django database models on a page before already, using a loop. The issue I've encountered is I want to have multiple (three) of these models on a row kinda like if I used a flex box with three divs inside except because of the way the loop is running all three divs are the same. Any ideas on how to change the code for the divs to all be different models? Here is my code : Here is my item-store.html (Html Page to display the items) : {% for item in items %} <div class="triple-item-container"> <div class="single-item-container"> <div><p>{{item.name}}</p></div> <div><p>{{item.details}}</p></div> </div> <div class="single-item-container"> <div><p>{{item.name}}</p></div> <div><p>{{item.details}}</p></div> </div> <div class="single-item-container"> <div><p>{{item.name}}</p></div> <div><p>{{item.details}}</p></div> </div> </div> {% endfor %} Here is my item-store.css (Css Page linked to the Html Page) : .triple-item-container{ margin-top: 300px; height: 200px; display: flex; flex-direction: row; justify-content: space-around; } .single-item-container{ padding: 10px; background-color: rgb(226, 215, 113); } Here is my models.py in case you need it : class item(models.Model): name = models.CharField(max_length=100, blank=False, null=False) details = models.CharField(max_length=1000, blank=True, null=True) price = models.DecimalField(blank=False, null=False, decimal_places=2, max_digits=20) tag_choices = ( ('bakery', 'bakery'), ('meat&seafood', … -
почему сериализатор меняет имя автора , на его айди? [closed]
Comments models.py class Comments(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Posts, on_delete=models.CASCADE) text = models.CharField(max_length=500) created = models.DateTimeField(auto_now=True) class META: fields = ['author', 'post', 'text', 'created']` user models.py class User(AbstractUser): status = models.CharField(max_length=120, default='it\s a default user status', null=False) avatar = models.ImageField(upload_to='Network_/static/avatar/') views.py def get_post(self): post = Posts.objects.get(id=self.GET.get('post_id')) post_likes_len = len(Like.objects.filter(product=post)) like_icon = "/static/image/likeHearthicon.png" if Like.check_user_liked(self, user=self.user, post=post): like_icon = "/static/image/likeHearthicon_after.png" post_comments = Comments.objects.filter(post=post) return JsonResponse({ 'post': serializers.serialize('json', [post]), 'Likes':post_likes_len, 'like_icon': like_icon, 'comments': serializers.serialize('json', post_comments) }, safe=False ) Я новичок в dango, и не совсем понимаю что , и из-за чего меняет имя автора комментария на его айди. до этого действия (serializers.serialize('json', post_comments)) все выводиться нормально : 'Test_user_3' но после сериализации вместо 'Test_user_3' я получаю '3' то есть айди может кто-нибудь обьяснить , или хотя бы кинуть ссылку для того чтобы моя ветряная башка хоть что-то поняла -
Django : Dynamically set dropdown options based on other dropdown selection in Django Model Forms
This is a common scenario in frontend where we want a dropdown options set with respect to another selection in another dropdown, but not getting a solution in django admin forms Scenario : django model: class CompanyEmployee(): """ An Emailed Report """ company = models.ForeignKey(Company, on_delete=models.CASCADE, ) employee = models.ManyToManyField(Employee, blank=True, verbose_name='Employes',) class Meta: unique_together = ( ('company', 'name'), ) so in CompanyEmailAdminForm company is in list_filter and Employee as filter_horizontal, that means company is a dropdown and employee as filter with multiple choice. The queryset for employee widget if instance.pk: self.fields['employee'].queryset =Employee.objects.filter(company=instance.company) else: self.fields['employee'].queryset =Employee.objects.all() Company and Employee have a relation. So from company I can get the related Employee records. The issue is in add form where I don't have a saved instance. My requirement is when I select a company say 'ABC' I should get only records related to 'ABC' in the Employee filter. If onChange i can get the value back in the form I can re-evaluate the employee queryset. With django.JQuery the values in the employee section is not remaining permanently. -
How to get "captured values" from a url in get_absolute_url model in django
I have this url: path('<slug:slug>/<slug:product_slug>_<int:pk>/', ProductDetailView.as_view(), name='detail'), and I need access to < slug:slug > in product's get_absolute_url, this slug can be any of user's slug, is not from products. Is for generate the products breadcrumb urls like this: /user-slug/product-slug_product-id/ def get_relative_url(self): return reverse('custom_catalogue:detail', kwargs={ slug: kwargs['slug']??, 'product_slug': self.slug, 'pk': self.id}) any help I will appreciate -
Django ORM: calculation only inside databse-query possible?
I have rather simple dataset that's containing the following data: id | aqi | date | state_name 1 | 17 | 2020-01-01 | California 2 | 54 | 2020-01-02 | California 3 | 37 | 2020-01-03 | California 4 | 29 | 2020-01-04 | California What I'm trying to achieve is the average aqi (air-quality-index) from april 2022 minus the average aqi from april 2021, without using multiple queries. Is this even possible or should I use two queries and compare them manually? From my understanding, I should use the Q-Expression to filter the correct dates, correct? AirQuality.objects.filter(Q(date__range=['2021-04-01', '2021-04-30']) & Q('2022-04-01', '2022-04-30')) Thanks for your help and have a great day! -
Why only 1 value is bound?
The meaning of the program is to select analogues from the list and link them. I always bind only 1 value (to itself). How to fix it My view: def editpart(request, id, **kwargs): if request.method == 'POST': part.name = request.POST.get("name") part.description = request.POST.get("description") analogs = Part.objects.all() for analogs_zap in analogs: zap = analogs_zap.analog part.analog.add(part.id) My model: class Part(models.Model): name = models.CharField('Название', max_length=100) analog = models.ManyToManyField('self', blank=True, related_name='AnalogParts') -
Pytest: Test user-editing view, object is not updating
I want to test my account_edit view, if the user's/customer's info is being updated properply. I'm new to pytest. View: @login_required def account_edit(request): if request.method == "POST": user_form = UserEditForm(instance=request.user, data=request.POST) if user_form.is_valid(): user_form.save() else: user_form = UserEditForm(instance=request.user) return render(request, "account/user/edit_account.html", {"user_form": user_form}) Factory: class CustomerFactory(factory.django.DjangoModelFactory): class Meta: model = Customer django_get_or_create = ("email",) email = "user1@gmail.com" name = "user1" mobile = "123456789" password = "user1" is_active = True the test_account_views.py: @pytest.mark.django_db def test_account_edit_post(client, customer_factory): user = customer_factory.create() client.force_login(user) response = client.post( "/account/edit/", data={ "name": "newname", "email": "newemail@gmail.com", }, ) print(user.name) assert response.status_code == 200 When Im printing out the email print(user.name) Im expecting it to be updated with newname. However receiving the old one (user1) AND the response status is also OK: 200. So it seems the problem is just that the user isn't updating. The problem is with testing code, not the django app itself(checked it). Thanks in advance for any help. -
Django models. Get all objects and sum duplicates
I have table in MySQl which describe Retail Demand models. row_num full_name quantity 1 4Пивовара - Похищение человеков инопланетянами (IPA - White. OG 17%, ABV 7,5%, IBU 67) 1 2 AF Brew - Autumn Fever Dreams: November (Sour - Fruited. ABV 7%) 1 3 Big Village - ABC-Kölsch (Kölsch. ABV 5.5%, IBU 20) 1 4 Big Village - Distrust (Pale Ale - New England. OG 15%, ABV 6%, IBU 25) 1 5 Big Village - Imaginarium (IPA - American. OG 16%, ABV 7%, IBU 60) 1 6 Big Village - Quartet X (Belgian Quadrupel. ABV 12,5%) 1 7 Gravity Project - It's A Mango (Cider - Other Fruit. ABV 5%) 1 9 Jaws - APA (Pale Ale - American. OG 13,5%, ABV 5%, IBU 43) 2 10 Jaws - Pale Ale (Pale Ale - English. OG 13%, ABV 5,2%, IBU 25) 1 11 Jaws - Pale Ale (Pale Ale - English. OG 13%, ABV 5,2%, IBU 25) 1 12 Jaws - Populism [Mosaic] (IPA - New England. OG 15%, ABV 6,5%, IBU 20) (Банка 0,45) 1 13 Jaws - Атомная Прачечная (IPA - American. OG 16%, ABV 7,2%, IBU 101) 4 14 Saldens - American Pale Ale Tears of Liberty … -
core error - Script timed out before returning headers: wsgi.py
I'm running a Django app on Apache/2.4.6 (CentOS) with mod_wsgi. When I visit my domain, after few minutes I get "Internal Server Error". The log file shows the following error - [core:error] [pid 9361] [client 132.72.41.107:55906] Script timed out before returning headers: wsgi.py The config file in sites-enable folder - <VirtualHost *:80> ServerName www.meshi1.cs.bgu.ac.il ServerAlias meshi1.cs.bgu.ac.il DocumentRoot "/var/www/meshi1.cs.bgu.ac.il" ErrorLog /var/www/meshi1.cs.bgu.ac.il/log/error.log CustomLog /var/www/meshi1.cs.bgu.ac.il/log/requests.log combined Alias /static /home/cluster/orelhaz/bin/rom_deshe/djangonautic1/static <Directory /home/cluster/orelhaz/bin/rom_deshe/djangonautic1/static> Require all granted </Directory> WSGIDaemonProcess djangonautic python-home=/home/cluster/orelhaz/bin/rom_deshe/myenv/lib/python3.6 WSGIProcessGroup djangonautic WSGIScriptAlias / /home/cluster/orelhaz/bin/rom_deshe/djangonautic1/djangonautic/wsgi.py <Directory /home/cluster/orelhaz/bin/rom_deshe/djangonautic1/djangonautic> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> Thanks! -
Nested Array search in MongoDB/PyMongo while using aggregate
I am trying to search for a keyword inside array of arrays in a mongo document. { "PRODUCT_NAME" : "Truffle Cake", "TAGS": [ ["Cakes", 100], ["Flowers", 100], ] } Usually, i would do something like this and it would work. db.collection.find( {"TAGS":{"$elemMatch":{ "$elemMatch": {"$in":['search_text']} } }} ) But now, I changed this query to an aggregate based query due to other requirements. I've tried $filter , $match but not able to replicate the above query exactly.. Can anyone convert the above code so that it can directly work with aggregate? (I use PyMongo) -
Newer version of botocore breaks integration test
Imagine the follow functions, that should upload and copy something to S3 class TestAttachments(TestCase): # YAML is the only serializer supporting binary @override_env(AWS_DEFAULT_REGION='eu-west-1') # So the test doesn't fail depending on env. vars @my_vcr.use_cassette(serializer='yaml') def test_copy_attachments_to_sent_folder(self): with self.assertRaises( CopyAttachmentException, msg="Failed to copy attachments to sent folder for attachment URL: http://example.com/foo.jpg" ) as cm: copy_attachments_to_sent_folder(["http://example.com/foo.jpg"]) self.assertEqual(cm.exception.__cause__.__class__, InvalidAttachmentURL) TEST_UUIDS = ["uuid_0"] with patch.object(uuid, 'uuid4', side_effect=TEST_UUIDS): result = copy_attachments_to_sent_folder([ f"https://{settings.MESSAGE_ATTACHMENTS_S3_BUCKET}.s3.amazonaws.com/attachments/Test+video.mov" ]) self.assertEqual( [AttachmentMetadata( s3_key=f"attachments/sent/{TEST_UUIDS[0]}/video/quicktime/Test video.mov", filename="Test video.mov", mime_type="video/quicktime", size=178653, )], result ) It should test the following function: def copy_attachments_to_sent_folder(urls: List[str]) -> List[AttachmentMetadata]: # Copy the attachment to the sent folder in parallel with futures.ThreadPoolExecutor(max_workers=4) as executor: urls_by_future = {executor.submit(copy_attachment_to_sent_folder, url): url for url in urls} results_by_url = {} for future in futures.as_completed(urls_by_future.keys()): try: results_by_url[urls_by_future[future]] = future.result() except Exception as e: raise CopyAttachmentException( f"Failed to copy attachments to sent folder for attachment URL: {urls_by_future[future]}" ) from e # The futures can complete out-of-order, so we need to re-order them to match the original order here return [results_by_url[url] for url in urls] Which finally uses this function inside: def copy_attachment_to_sent_folder(url: str) -> AttachmentMetadata: aws_session = attachments_aws_session() s3_client = aws_session.client("s3") parse_result = urlparse(url, allow_fragments=False) # Allow both with/without AWS region in hostname attachment_hostname_regex = fr"{settings.MESSAGE_ATTACHMENTS_S3_BUCKET}\.s3\.(.+?\.)?amazonaws\.com" … -
How to use for loop inside map python
I have a function that returns a list of numbers. But I know in other languages like JS we don't need to set a variable like c = 0. I see about map in python but I don't know how can I do it Here is my function: def get_bought_passenger_count(self): c = 0 for book in self.bookings.all(): c += book.passenger_count return c I want to do this with map function -
Django orm for multiple foreign key
I have a existing old database and I am trying to join 3 tables with django orm: class Orderlist(models.Model): record = models.IntegerField(db_column='RECORD', unique=True, primary_key=True) vechileid = models.CharField(db_column='vechileid ', max_length=10, blank=True, null=True) class Orderitem(models.Model): ' ' orderid= models.ForeignKey('Orderlist', models.DO_NOTHING, db_column='ORDERID', blank=True, null=True) ' ' class Vehicle(models.Model): ' ' vechileid = models.ForeignKey('Orderlist', models.DO_NOTHING, db_column='vechileid ', blank=True, null=True) ' ' I am trying to join as below: Select ... from Orderlist LEFT OUTER Orderitem ON Orderlist.record=Orderitem.orderid, LEFT OUTER JOIN Vehicle ON Orderlist.vechileid =Vechile.vechileid WHERE ... every time i try to join orderlist and vehicle it joins as orderlist.record=vehicle.vechileid How can i write the above sql query into django orm? -
Django: "SELECT field, count(field) FROM table GROUP BY field" being field an object
I've got next issue. Having next tables: products_table: id product_type serial_number 1 1 FX2002 2 1 FX2003 3 2 FX2004 4 2 FX2005 5 2 FX2006 product_types_table: id element 1 laptop 2 mouse 3 screen In products_table, product_type is a foreign key to product_types_table. I need to execute next query: SELECT product_type, count(product_type) AS quantity FROM products_table And get: product_type quantity 1 2 2 3 I've tried: queryset = products_table.objects.all().values("product_type").annotate(quantity=Count("product_type")) What returns next queryset: [{'product_type':1, 'quantity':2}, {'product_type':2, 'quantity':3}] I need 'product_type' field to be an object instead of integer, so element field can be called as: element = queryset[0]['product_type'].element Getting 'laptop' if I print element variable. I need to convert this data into JSON as well, and I need next response: [ { id: 1, product_type: { id: 1, element: 'laptop' }, serial_number: 'FX2002' }, { id: 2, product_type: { id: 1, element: 'laptop' }, serial_number: 'FX2003' }, { id: 3, product_type: { id: 2, element: 'mouse' }, serial_number: 'FX2004' }, { id: 4, product_type: { id: 2, element: 'mouse' }, serial_number: 'FX2005' }, { id: 5, product_type: { id: 2, element: 'mouse' }, serial_number: 'FX2006' } ] How can I do it??? Thank all of you for your time. -
Django - database exception - custom exception handler
Does Django provide a possibility to implement a custom exception handler over the database layer? I want to catch database exceptions, check error codes, and on some error codes -> wait for a while and retry the query. Is it possible in the Django? -
Two variables in single url pattern without '/'
I want to add 2 variables in single url pattern without '/' like this /<location-name>-<cityname>/. both are slugs. Location name can have 2-3 words and city name also can have 1-4 words. I tried path(/<location-name>-<cityname>/,..) but django is taking last word as city and rest as location. Like If I try /location-name1-city-name2/ then location-name-city is location and name2 is city. How can I do this? -
How to fix 'ManyToManyDescriptor' object has no attribute 'add'?
My viev def editpart(request, id, **kwargs): PartAllView = Part.objects.order_by('-id') part = Part.objects.get(id=id) form = PartForm(request.POST, request.FILES) if request.method == 'POST': part.name = request.POST.get("name") part.description = request.POST.get("description") analogs = Part.objects.all() for analogs_zap in analogs: zap = analogs_zap.analog Part.analog.add(Part.id) My model class Part(models.Model): name = models.CharField('Название', max_length=100) analog = models.ManyToManyField('self', blank=True, related_name='AnalogParts') -
No module named ldap.filter in /usr/local/lib/python3.8/dist-packages/django_auth_ldap/config.py
This error occurs when i was trying to set up a new django project intergreted with django_auth_ldap in Ubuntu server, the environment & prerequisite for ldap are all installed successfully.The other project on the same server runs properly with no issues. Really need help full error message below: Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.8/dist-packages/django/core/management/commands/runserver.py", line 74, in execute super().execute(*args, **options) File "/usr/local/lib/python3.8/dist-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.8/dist-packages/django/core/management/commands/runserver.py", line 81, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/usr/local/lib/python3.8/dist-packages/django/conf/__init__.py", line 87, in __getattr__ self._setup(name) File "/usr/local/lib/python3.8/dist-packages/django/conf/__init__.py", line 74, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.8/dist-packages/django/conf/__init__.py", line 183, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/ldap/project/ldap/ldap/settings.py", line 17, in <module> from django_auth_ldap.config import LDAPSearch File "/usr/local/lib/python3.8/dist-packages/django_auth_ldap/config.py", line 36, in <module> import ldap.filter ModuleNotFoundError: No module named 'ldap.filter' During handling of the above exception, another exception occurred: …