Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how delete object in djago with yes no in sweetify
I want to delete the desired object with the help of the sweetify package when the user presses the yes button, but nothing happens. Does anyone know the reason? How can I fix it?? This is the code ` class DeleteOrder(DeleteView): model = OrderDetail template_name = 'dashboard/dashboard_order_list.html' success_url = reverse_lazy('dashboard_user:order-list') def delete(self, request, *args, **kwargs): try: sweetify_response = sweetify.sweetalert(request, 'آیا مطمٔنید؟', text="آیا واقعا میخواهید سفارش مورد نظر حذف شود؟", persistent='بله حذف کن', cancel='نه بمونه', dangerMode=True, timer=15000, focusConfirm=True, confirmButtonText='حذف', cancelButtonText='انصراف', showCancelButton=True) if sweetify_response.get('did_confirm'): messages.success(request, 'سفارش مورد نظر با موفقیت حذف شد') response = super().delete(request, *args, **kwargs) return response elif sweetify_response.get('did_cancel'): return redirect(self.success_url) else: messages.warning(request, 'سفارش مورد نظر حذف نشد') return redirect(self.success_url) except Exception as e: messages.error(request, str(e)) return redirect(self.success_url) def get_success_url(self): return self.object.get_absolute_url() ` First, I tried to delete the object without checking, which was deleted before the user confirmed the object, but then I changed the code so that it checks the button that the user pressed and then deletes it, but nothing happens. I tried a lot, but I couldn't fix it. -
set a value in request body from lua script on kong
I am using kong as API gateway and running a lua script to modify my api request. In my API request from server I expect, a authorization token & content type in header. I wish to add a field, user_id in my API request body. How can I do that? my request from server has only authorization & content-type as you can see in the image (click here) also my body has nothing from server as you can see in image (click here) but I want to add user_id in this Api request body(raw) via lua script. P.s. I am then reading the body in my django application as request_body = json.loads(request.body.decode('utf-8')) pls guide. in my lua script I am trying local form_data, err, mimetype = kong.request.get_body() form_data["customer_id"] = customer_obj.user_id form_data = cjson.encode(form_data) kong.service.request.set_raw_body(form_data) I get { "message": "An unexpected error occurred" } in response with the above code. -
Django API and Portal - Serving from using CNAME and diferent apps
I am building and application that will have a Portal for our customers. Besides that thye could consume information using an API. I would like to serve the Portal in the root domain, and the api using a CNAME like api.domain.com. SO basically I have two questions: Is it a best practice to have two apps: one for the api and other to server the portal? How could i route the CNAME ( api.domain.com) in my settings.py file? -
My question is: I have an API in Django, I want to receive my JSON from the API, containing an ID that encompasses each JSON
I am not able to create an API whose ID of each object added to it is encompassing it, the ID is being created INSIDE the JSON, and I don't want that. For example, this is the code that i have right now: [ { "id": 1, "event_image": "/event_images/TheTown.png", "event_name": "The Town", "event_price": "500.00", "event_date": "2, 3, 7, 9 e 10 de Set", "event_time_start": "14:00:00", "event_time_ends": "02:00:00", "event_location": "Av. Sen. Teotônio Vilela, 261 - Interlagos, São Paulo - SP, 04801-010", "event_description": "The Town é um festival de música idealizado pelo empresário brasileiro Roberto Medina – mesmo criador do Rock in Rio – pela primeira vez em 2023. É reconhecido como um dos maiores festivais musicais do Brasil. O festival é localizado no Autódromo de Interlagos em São Paulo, mesmo local onde é realizado o Lollapalooza." }, { "id": 17, "event_image": "/event_images/CasaDeShow_HD2PgOZ.jpg", "event_name": "The Town", "event_price": "200.00", "event_date": "2, 3, 7, 9 e 10 de Set", "event_time_start": "14:00:00", "event_time_ends": "02:00:00", "event_location": "Av. Sen. Teotônio Vilela, 261 - Interlagos, São Paulo - SP, 04801-010", "event_description": "The Town é um festival de música idealizado pelo empresário brasileiro Roberto Medina – mesmo criador do Rock in Rio – pela primeira vez em 2023. É … -
How to solve django encoding with 'idna' codec failed (UnicodeError: label empty or too long) problem?
Hello Stack Overflow friends! I hope somebody can help with an advice on how to fix this issue. Same error i see in password reset, and in the register verification, when the email has to be sent. I am using console instead of smtp at the moment though, but it is not working anyhow, the problem is still present. Here is my custom user model from accounts app. models.py from django.db import models # define custom user from django.contrib.auth.models import AbstractUser class User(AbstractUser): email = models.EmailField(unique=True, max_length=50) username = models.CharField(unique=True, max_length=20) note = models.TextField(max_length=200, null=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.email forms.py from django import forms from .models import User from django.contrib.auth.forms import UserCreationForm, SetPasswordForm # user register form class UserRegisterForm(UserCreationForm): class Meta: model = User fields = [ 'email', 'username', 'password1', 'password2', ] Then i import the model and the form to views.py I also define 'accounts.USER' in settings with AUTH_USER_MODEL. views.py from django.shortcuts import render, redirect from .forms import UserRegisterForm, UserLoginForm, ChangePassword, EditProfileForm from django.contrib import messages # authenticate user from django.contrib.auth import authenticate, login, logout, get_user_model from django.conf import settings # For email verification system from .token import user_tokenizer_generate from django.contrib.sites.shortcuts import … -
How to test a patch request in Django Rest Framework?
I have two test cases in Django Rest Framework: One is a post and one is a patch testcase. The post works without a problem, but the patch trows a problem. In reality they both work. with open(os.path.join(self.path, "..", "..", "plugin/test_files/icons.png"), 'rb') as file_obj: document = SimpleUploadedFile( file_obj.name, file_obj.read(), content_type='image/png') re = self.patch(f"/api/units/{unit_id}/", {"files": [document]}, content_type=MULTIPART_CONTENT) self.assertIn('pictures', re) self.assertEqual(len(re["pictures"]), 1) # Fails with 0 != 1 with open(os.path.join(self.path, "..", "..", "plugin/test_files/icons.png"), 'rb') as file_obj: document = SimpleUploadedFile( file_obj.name, file_obj.read(), content_type='image/png') re = self.post("/api/units/", {"company_id": 1, "name": "test", "address_id": 1, "files": [document]}, content_type=MULTIPART_CONTENT) self.assertIn('pictures', re) self.assertEqual(len(re["pictures"]), 1) My views are in both cases the default UpdateMixin and CreateMixin, the serializer is the same. It appears that there is no request.data on the patch request. How can I achieve my data actually arriving in the backend here? -
DRF - return 404 via get_queryset or raise serializer error
I am adding a custom action to a ModelViewSet in Django Rest Framework which allows users to cancel a particular booking. There are several criteria for whether a booking can be cancelled or not - for example, it needs to not already be cancelled. Is there a "correct" way of dealing with this situation? Should I:- a) filter out the bookings that have already been cancelled in the get_queryset() method so that the API returns an HTTP 404 for an already-cancelled booking or b) use a different serializer for cancelling bookings and raise a ValidationError (and therefore an HTTP 400) in the validation if the booking has already been cancelled or c) something else entirely ? -
I am unable retrieve the data from post request
I am trying to retrieve the data from the post request, but it just not comming.. it went to success page without returning data Code: views.py from django.shortcuts import render,redirect from django.http import HttpResponse def page1(request): if request.method=="POST": name=request.POST['input1'] print(name) else: return render(request,'add_image/page1.html') def page2(request): return render(request,'add_image/pag2.html') page1.html <!DOCTYPE html> <html> <head> <title>Page1</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous"> </head> <body> <form action="/add/page2/" method="POST"> {% csrf_token %} <input type="text" name="input1"> <input type="submit" name="" value="Submit"> </form> </body> </html> page2.html <!DOCTYPE html> <html> <head> <title>Page2</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous"> </head> <body> <h1>Welcome</h1> </body> </html> I am trying to retrieve the data from post request but it is not comming, I even tried get and cookies method but still not working, -
Django API Fetch data from one table another table through nested Foreign key
Does anyone know how to get userprofile detials from 'PersonalDetails' through by using the User table Modal Connection flow User -> Representative -> PersonalDetails Retrive data flows User <- Representative <- PersonalDetails -
Django Rest Framework's Nested Serializers POST Request ForeignKey Error
I'm working on a blood analysis lab availability check project, I'm using DRF(Django Rest Framework) to build the API. I'm facing Not Null Constraints problems whenever i try to post data that contains a OneToOne relationship(ForeignKey). here are the concerned models in my models.py file: class Exam(models.Model): name = models.CharField(max_length=100,unique=True,blank=False) abbrv = models.CharField(max_length=100,unique=True,blank=False,null=False) price = models.IntegerField(blank=False,null=False) description = models.TextField(max_length=1000,blank=False,null=False) available = models.BooleanField(blank=False,null=False,default=True) _type = models.CharField(max_length=64,blank=False,null=False) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.abbrv class Order(models.Model): patient = models.CharField(max_length=100,blank=False) code = models.CharField(max_length=100,unique=True,blank=False,null=False) total = models.IntegerField(blank=False,null=False) done = models.BooleanField(blank=False,null=False,default=True) exams = models.ForeignKey(Exam, on_delete=models.CASCADE,related_name='ordered_exams') ordered_at = models.DateTimeField(auto_now_add=True) and here are the concerned serializers in my serializers.pyfile: class ExamSerializer(serializers.ModelSerializer): class Meta: model = Exam fields = '__all__' class OrderSerializer(serializers.ModelSerializer): exams = ExamSerializer(many=0,read_only=1) class Meta: model = Order fields = '__all__' and here are my concerned views in my view.py file: class OrdersView(APIView): def get(self, request): order = Order.objects.all() serializer = OrderSerializer(order, many=True) return Response(serializer.data) def post(self,request): serializer = OrderSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) and here is my available exams that are returned from a GET request: [ { "id": 1, "name": "fns", "abbrv": "fns", "price": 500, "description": "Formule et Numerisation Sanguine", "available": true, "_type": "hemo", "created_at": "2023-04-26T14:16:13.301701Z" } ] and whenever … -
How am I misunderstanding Django's get_or_create function?
We have a Django project that has a bunch of experiments, and each experiment can have zero or more text tags. The tags are stored in a table, and there is a many-to-many relationship between experiments and tags: class Tag(models.Model): text = models.TextField(max_length=32, null=False, validators=[validate_unicode_slug], db_index=True, unique=True) class Experiment(models.Model): ... tags = models.ManyToManyField(Tag) If I add a tag to an experiment with get_or_create() it does the right thing, filling in the tag table and the joining table. If I remove the tag from the experiment with remove() it also does the right thing by removing just the row from the joining table and leaving the tag table intact. But if I later come to re-add the tag to the experiment, it throws a uniqueness constraint error because it's trying to re-add the tag to the tag table. E.g: tag, created = experiment.tags.get_or_create(text="B") experiment.tags.remove(*experiment.tags.filter(text="B")) tag, created = experiment.tags.get_or_create(text="B") # It fails the uniqueness test here. Removing the uniqueness constraint just means it adds a new tag with identical text. So is it possible to add and remove tags arbitrarily by just modifying the joining table if a tag already exists? -
how to send request to ocpp1.6 charger using django channel server
I created a django web application and i use django channel to establish connection with ocpp1.6 charger. in consumers.py in receive_json function im receiving chargers requests and sending response successfully, problem: i need to send request to charger from my django server like remote start transaction request, how i can becoz in consumers.py file the receive function is only send response when they receive data i want when a client from my front end click on start button then a request sent to charger for remote start transaction -
execution of the ".py" script on a django web page
I need to run a script (on python) that will output information to a web page (on django), now by writing a link to the script, I just get the output of the script text on the page index.html <html> <head> <title></title> </head> <frameset rows=100% > <frameset rows=76%,24% > <frameset cols=64%,36% > <frame name=reports src="{% url 'core:reports-name' %}"> <frame name=fg_log src= > </frameset> <frameset cols=64%,36% > <frame name=fp_log src= > <frame name=ls src= > </frameset> </frameset> </frameset> </html> **urls.py** from django.urls import path, include from . import views app_name = 'core' urlpatterns = [ path('', views.index, name='index'), path('reports', views.reports, name='reports-name') ] **views.py** from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator from django.shortcuts import get_object_or_404, redirect, render User = get_user_model() #@login_required def index(request): template = 'core/index.html' return render(request, template) def login(request): pass #@login_required def reports(request): template = 'cgi/reports.py' return render(request, template) I was prompted that the solution should be at the nginx level, that with nginx you need to prescribe a condition for script execution on a web page, but I did not find a solution I only found a solution for PHP, but I couldn't make it under pyhton location ~ \.py$ … -
how to assign my profile user to be a User instance
i have 2 applications in django project "accounts" for managing user and authetications and the "BP" for managing the BusinessPlan every application have her own models, urls, and views this is accounts/models.py : class User(AbstractBaseUser): email = models.EmailField(unique=True, max_length=255) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' class Meta: app_label = 'accounts' def __str__(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin this is accounts/views.py def signup(request): form = RegistrationForm() if request.method == 'POST': registration_form = RegistrationForm(request.POST) if registration_form.is_valid(): user = registration_form.save(commit=False) user.is_active = True user.save() user_id=user.id return redirect(reverse('bp:profile',kwargs={'user_id':user_id})) return render(request,'signup.html',{'form':form}) this is bp/models.py : class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #.....other fields.... ther is other fields like name, birthdate, phone, .... this is bp/views.py: def profile(request,user_id): if request.method =='POST': user=User.objects.get(id=user_id) form = NewProfileForm(request.POST) if form.is_valid(): profile=form.save(commit=False) profile.user=user profile.save() else: form=NewProfileForm() return render(request,'profile.html',{'form':form}) i create the user and it's done then i try to add the profile after validating every data it send me this message: how to fix it -
A lot of similar queries bcs of for loop Django
I have for loop in my get_queryset function and i'm parsing info from request into my django template but for some reason bcs i try to filter by GUID i got 21 similiar sql queries I was trying to get CleanSections before my for loop but that didnt help Any tips how can i solve that? views.py def get_queryset(self): session = requests_cache.CachedSession('budget_cache', backend=backend, stale_if_error=True, expire_after=360) url = config('API') + 'BUDGET' response = session.get(url, auth=UNICA_AUTH) response_json = None queryset = [] if response_json is None: print('JSON IS EMPTY') return queryset else: all_sections = CleanSections.objects.all() for item in response_json: my_js = json.dumps(item) parsed_json = ReportProjectBudgetSerializer.parse_raw(my_js) if parsed_json.ObjectGUID == select_front: obj = parsed_json.ObjectGUID else: continue for budget in parsed_json.BudgetData: budget.SectionGUID = all_sections.filter(GUID=budget.SectionGUID) budget.СompletedContract = budget.СompletedContract * 100 budget.СompletedEstimate = budget.СompletedEstimate * 100 queryset.append(budget) return queryset -
How to get radio button value using django without submit button
<body> <form action="" method="post"> {% csrf_token %} <input type="radio" name="course" value="C" />C <br> <input type="radio" name="course" value="CPP" />CPP <br> <input type="radio" name="course" value="DS" />DS <br> </form> {{res}} </body> views.py def user(request): if 'CPP' in request.POST: print("CPP") return HttpResponseRedirect(request.path_info) Is there any solution to pass values to the views when the radio button is checked when submit button is not there -
Linking To Related Articles In Django
I have a Django blog, and each article is associated with a certain category. On the detail page of each article, there is a card on the right side. This card has a header of "Related Articles" and has a list of the five most recent articles under that same category as the article currently being viewed. Below this list of related articles is a button that should link the user to all articles under that same category. But I can't seem to make the link to serve its desired purpose. On my index page, I can click on any category and get directed to a list of similar articles, but I can't achieve the same functionality from my detail page. How do I fix this? Below are the relevant codes. In my models.py, class Category(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(unique=True, blank=True) class Meta: verbose_name_plural = 'categories' def __str__(self): return self.name def save(self, *args, **kwargs): # generate a slug based on the post title self.slug = slugify(self.name) super(Category, self).save(*args, **kwargs) class Post(models.Model): image = models.ImageField() title = models.CharField(max_length=255) slug = models.SlugField(unique=True, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='posts', default='uncategorized') post = models.TextField() date = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(User, blank=True, related_name="post_likes") … -
ox_Oracle with database 11g Django problem with view name 'ORDER'
In my project im using cx_Oracle to connect and recive data from ORACLE 11g database. In database i have view 'ORDER' and every time im trying to make query with that name i have error ORA-01722: invalid number, even with RAW query. I cant change view name. Can anybody have solution ? Django ver. 3.2.18 cx_Oracle ver. 8.3.0 Instant Client Oracle 21.9 Error ocures even with raw querry. Models in Django are same as view shema. -
Django. How to remove duplicate requests in a Modelform
model. py class MyModel(models.Model): name = models.CharField() attribute1 = models.ForeignKey(ModelOne) attribute2 = models.ForeignKey(ModelOne) attribute3 = models.ForeignKey(ModelTwo) forms.py class MyModelForm(ModelForm): class Meta: model = MyModel fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) ModelOne_choice = [(fields.id, fields.__str__()) for fields in ModelOne.objects.all()] self.fields['attribute1'].choices = ModelOne_choice self.fields['attribute2'].choices = ModelOne_choice My current model has many foreign keys including different attributes pointing to the same foreign key. django debug_toolbar shows about 10 requests when creating a form. How can this number be minimized? I have used ModelOne_choice for repeated foreign keys. Tried Raw requests. As I understand it, when a project is launched into production, such a number of calls to the database is very bad -
how to send a list of data with django swagger
hi I want to send a list of id in the form of: ["1", "2", "3"] with django swagger... i tried this way first: views.py @swagger_auto_schema(**swagger_kwargs["payment_expenses"]) @action(methods=["post"], detail=True, parser_classes=(FormParser, MultiPartParser)) def payment_expenses(self, request, pk): items = request.data["items"] print(items) but out put is in the form of ["1,2,3"] -
Why adding index to django model slowed the exectuion time?
I've added the index to my django model in order to make the queries on it a little bit faster but the execution time actually went up: from autoslug import AutoSlugField from django.db import models class City(models.Model): name = models.CharField(max_lenght=30) population = models.IntegerField() slug = AutoSlugField(populate_from="name") class Meta: indexes = [models.Index(fields=['slug'])] And I've used this function to calculate execution time for my CBV: def dispatch(self, request, *args, **kwargs): start_time = timezone.now() response = super().dispatch(request, *args, **kwargs) end_time = timezone.now() execution_time = (end_time - start_time).total_seconds() * 1000 print(f"Execution time: {execution_time} ms") return response Before adding indexes to Meta class the execution time on City.objects.all() in my CBV was: Execution time: 190.413 ms But after adding it it became: Execution time: 200.201 ms Is there any idea why that happens? Perhaps it is unadvisable to use indexes on slug fields? -
Django Docker Postgresql database import export
I have a problem with postgresql database. I just want to able to export and import database like .sql file. But when using command line I am able to get .sql database file but when I'm trying to import it to database it's giving syntax errors in sql file. I can try to fix syntax errors in sql file but I don't want to solve this problem it like that. I need to get exported sql file without any errors and to be able to import it without any issue. What can be a problem? Postgresql version:postgres:14.6 For example here is auto generated sql code by exporting db as sql file. it gives syntax error in this line : "id" bigint DEFAULT GENERATED BY DEFAULT AS IDENTITY NOT NULL, DROP TABLE IF EXISTS "core_contact"; CREATE TABLE "public"."core_contact" ( "id" bigint DEFAULT GENERATED BY DEFAULT AS IDENTITY NOT NULL, "first_name" character varying(50) NOT NULL, "last_name" character varying(50) NOT NULL, "company_name" character varying(50) NOT NULL, "email" character varying(128) NOT NULL, "message" text NOT NULL, "created_at" timestamptz NOT NULL, CONSTRAINT "core_contact_pkey" PRIMARY KEY ("id") ) WITH (oids = false); But, when I change it manually like that : "id" bigint NOT NULL, And … -
problem with creating APIView for celery flower dashboard
I have Django, DRF and React application with few endpoints. I'd like to create APIView that redirects user to flower pages. The flower urls should be hosted under www.myapp.com/flower. I've created docker container with django, react, celery-beats, celery-worker, flower and nginx images and I can run them normally however I am not sure how to do it on lcoud. I am using Azure App Service. I have 2 files in my nginx folder but: nginx.conf server { server_name myapp; location / { proxy_pass http://myapp.com/flower; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } } Dockerfile FROM nginx:1.17.4-alpine RUN rm /etc/nginx/conf.d/default.conf ADD nginx.conf /etc/nginx/conf.d -
Post Form object has no attribute 'cleaned'
This is my Post Form from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = '__all__' def clean_slug(self): return self.cleaned['slug'].lower() Here is my Traceback: Traceback (most recent call last): File "django\core\handlers\exception.py", line 56, in inner response = get_response(request) File "django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "django\views\generic\base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "django\views\generic\base.py", line 142, in dispatch return handler(request, *args, **kwargs) File "E:\Django Unleashed\suorganizer\blog\views.py", line 28, in post if bound_form.is_valid(): File "django\forms\forms.py", line 205, in is_valid return self.is_bound and not self.errors File "django\forms\forms.py", line 200, in errors self.full_clean() File "django\forms\forms.py", line 437, in full_clean self._clean_fields() File "django\forms\forms.py", line 452, in _clean_fields value = getattr(self, "clean_%s" % name)() File "suorganizer\blog\forms.py", line 11, in clean_slug return self.cleaned['slug'].lower() AttributeError: 'PostForm' object has no attribute 'cleaned' [26/Apr/2023 14:51:24] "POST /blog/create/ HTTP/1.1" 500 93820 -
Django LDAP Active Directory Authentification
Im trying to adjust my django project to connect to AD. Using libraries django-auth-ldap, ldap. Binding user is fine, creating and populating django user - ok. But in the end, authentification fails with next output: Binding as CN=bind,CN=Users,DC=ATK,DC=BIZ Invoking search_s('DC=ATK,DC=BIZ', 2, '(sAMAccountName=admin)') search_s('DC=ATK,DC=BIZ', 2, '(sAMAccountName=%(user)s)') returned 1 objects: cn=admin,cn=users,dc=atk,dc=biz Binding as cn=admin,cn=users,dc=atk,dc=biz Binding as CN=bind,CN=Users,DC=ATK,DC=BIZ cn=admin,cn=users,dc=atk,dc=biz is a member of cn=django-admins,cn=users,dc=atk,dc=biz Creating Django user admin Populating Django user admin Caught LDAPError while authenticating admin: OPERATIONS_ERROR({'msgtype': 111, 'msgid': 6, 'result': 1, 'desc': 'Operations error', 'ctrls': [], 'info': '000020D6: SvcErr: DSID-031007E5, problem 5012 (DIR_ERROR), data 0\n'}) My settings.py file is below: AUTHENTICATION_BACKENDS = [ 'django_auth_ldap.backend.LDAPBackend', "django.contrib.auth.backends.ModelBackend", ] AUTH_LDAP_SERVER_URI = "ldap://BORUM.ATK.BIZ" AUTH_LDAP_BASE_DN = "DC=ATK,DC=BIZ" AUTH_LDAP_BIND_DN = "CN=bind,CN=Users,DC=ATK,DC=BIZ" AUTH_LDAP_BIND_PASSWORD = "***" AUTH_LDAP_USER_SEARCH = LDAPSearch( AUTH_LDAP_BASE_DN, ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)" ) # AUTH_LDAP_USER_DN_TEMPLATE = "cn=%(user)s,cn=users,dc=ATK,dc=BIZ" AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_DEBUG_LEVEL: 255, ldap.OPT_REFERRALS: 0, } AUTH_LDAP_USER_ATTR_MAP = { "username": "sAMAccountName", "first_name": "givenName", # "last_name": "sn", } AUTH_LDAP_GROUP_SEARCH = LDAPSearch( "DC=ATK,DC=BIZ", ldap.SCOPE_SUBTREE, "(objectCategory=group)", ) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr="cn") AUTH_LDAP_REQUIRE_GROUP = "CN=django-admins,CN=Users,DC=ATK,DC=BIZ" AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_superuser": "CN=django-admins,CN=Users,CN=ATK,CN=BIZ", "is_staff": "CN=django-admins,CN=Users,DC=ATK,DC=BIZ", } AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_GROUPS = True AUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600 Any ideas would be highly appreciated. Error number 000020D6 indicates that ERROR_DS_CANT_ACCESS_REMOTE_PART_OF_AD, I dont really understand how to treat that error, how binding …