Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django and parallel processing:
Versions: Python 3.5.1 Django 1.10 mysqlclient 1.3.10 mysql 5.7.18-0ubuntu0.16.04.1 (Ubuntu) Linux Mint 18.1 I have a large Django project where there's a setup script that adds a bunch of content to the database from some csv files. Once in a while, I need to reset everything, and re-add everything from these files. The data furthermore requires some post-processing once added. This however takes a while because the files are long and there's some unavoidable double loops in the code as well as many database queries. In many cases, the tasks are independent, and thus they should be possible to run in parallel. I looked around for parallel processing libraries and decided to use the very simple multiprocessing. Thus, the setup is quite simple. We define some function to run in parallel, and then call Pool. Simplified code: def some_func(input): #code inserting data into Django here pass with Pool(4) as p: p.map(some_func, [1, 2, 3, 4]) However, running the code results in database connection errors like these reported here, here, here: _mysql_exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query') It seems like the different threads/cores are trying to share one connection, or maybe the connection is not passed on to … -
Multiple pagination (ajax) not working for django-el-pagination
I have 2 querysets: Post and Comment. I'm using django-el-pagination to render these. Here's my views: def profile(request, user, extra_context=None): profile = Profile.objects.get(user__username=user) page_template = 'profile.html' if request.is_ajax(): user_queryset = request.GET.get('user_queryset') print('Queryset:', user_queryset) if user_queryset == 'user_posts': page_template = 'user_posts.html' elif user_queryset == 'user_comments': page_template = 'user_comments.html' else: pass print('Template:', page_template) user_posts = Post.objects.filter(user=profile.user).order_by('-date') user_comments = Comment.objects.filter(user=profile.user).order_by('-timestamp') context = {'user_posts': user_posts,'user_comments': user_comments, 'page_template': page_template} if extra_context is not None: context.update(extra_context) return render(request, page_template, context) I have an ajax call that find out which query set is being used. So when 'more comments' or 'more posts' (in the template) is being clicked to get more paginated objects, I know which queryset it's from. However when I use the above code and click 'more' for the ajax pagination, it appends the whole page, not the relevant child template (user_posts.html or user_comments.html). But theif request.is_ajax()` code block works fine; it prints the correct template to use so this shouldn't be happening. When I change that code block to this if request.is_ajax(): page_template = 'user_posts.html' The ajax pagination for Post works. However I'd like to add ajax pagination for Comment aswell. Why doesn't my initial if request.is_ajax() and how can I fix it? -
Django Docker simple container not running (nothing happens)
Here is a very simple Dockerfile I try to build and run. FROM python:3 WORKDIR /opt/todo COPY requirements.txt ./ RUN pip install -r requirements.txt COPY . . EXPOSE 8000 CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"] Firstly, I do docker build -t some_name . After that I do docker run -p 8000:8000 some_name and nothing happens. No output/no errors. But, if I do the same run command with -it flag it starts and works perfectly. Thanks in advance, any help is appreciated! -
editing user details in python django rest framework
I need code for editing user details like first_name , last_name by using APIView Class based. THe serializers.py and views.py are given under but it is not making the changes according to the user details . i am passing token for user authentication. Any assistance will be appreciated. Serializers.py class UserEditSerializer(serializers.Serializer): email = serializers.EmailField(required=True) first_name = serializers.CharField(required=True) last_name = serializers.CharField(required=True) def update(self, validated_data, instance): instance.first_name = validated_data.get('first_name') instance.email = validated_data.get('email') instance.last_name = validated_data.get('last_name') instance.save() return instance() Views.py class UserEditProfile(APIView): authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) def get_object(self): return self.request.user def post(self, request): self.object = self.get_object() serializer = UserEditSerializer(data=request.data) if serializer.is_valid(): self.object.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) -
django StreamingHttpResponse and apache wsgi - not working
I have the following streamed response: def reportgen_iterator(request, object_id): output_format = request.GET.get('output', 'pdf') response_data = { 'progress': 'Retrieving data...', 'error': False, 'err_msg': None } yield json.dumps(response_data) try: vendor_id, dr_datasets = get_dr_datasets( object_id=object_id, ws_user=settings.WS_USER, include_vendor_id=True, request=request ) except Exception as e: response_data.update({ 'error': True, 'err_msg': "Unable to retrieve data for report generation. Exception message: {}".format(e.message) }) yield "{}{}".format(DELIMITER, json.dumps(response_data)) time.sleep(BEFORE_STOP_ITERATION_SLEEP_SECS) raise StopIteration # data retrieved correctly, continue response_data['progress'] = 'Data retrieved.' yield "{}{}".format(DELIMITER, json.dumps(response_data)) domain = settings.DR['API_DOMAIN'] dr_id, delivery_opts = get_dr_ids(vendor_id=vendor_id) delivery_option_id = delivery_opts.get(output_format) run_idle_time = REST_RUN_IDLE_TIME_MS / 1000 or 1 headers = settings.DR['AUTHORIZATION_HEADER'] headers.update({ 'Content-Type': 'application/json', 'deliveryOptionId': delivery_option_id }) # POST request response_data['progress'] ='Generating document...' yield "{}{}".format(DELIMITER, json.dumps(response_data)) post_url = 'https://{domain}{rel_url}/'.format( domain=domain, rel_url=settings.DR['API_ENDPOINTS']['create'](ddp_id) ) header_img, footer_img = get_images_for_template(vendor_id=vendor_id, request=None) images = { 'HeaderImg': header_img, 'FooterImg': footer_img } data = OrderedDict( [('deliveryOptionId', delivery_option_id), ('clientId', 'MyClient'), ('data', dr_datasets), ('images', images)] ) payload = json.dumps(data, indent=4).encode(ENCODING) req = requests.Request('POST', url=post_url, headers=headers, data=payload) prepared_request = req.prepare() session = requests.Session() post_response = session.send(prepared_request) if post_response.status_code != 200: response_data.update({ 'error': True, 'err_msg': "Error: post response status code != 200, exit." }) yield "{}{}".format(DELIMITER, json.dumps(response_data)) time.sleep(BEFORE_STOP_ITERATION_SLEEP_SECS) raise StopIteration # Post response successful, continue. # RUN URL - periodic check post_response_dict = post_response.json() run_url = 'https://{domain}/{path}'.format( domain=domain, path=post_response_dict.get('links', … -
How to get relevant data from a parent model in Django?
I have 2 database tables, Prospects and Profile. They're related by a One-to-one foreign key relationship Model.py class Prospect(models.Model): profile = models.OneToOneField(Profile, on_delete=models.CASCADE, null=True, blank=True, related_name="profile_prospects") class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") In my view.py prospects = prospects[:50] I have a QuerySet of prospects (prospects is working correctly, exactly what I want), and I would like to retrieve a QuerySet of profiles based on the database model above. I tried profiles = Profile.objects.filter(profile_prospects__in = prospects) It returns an error of django.db.utils.ProgrammingError: subquery has too many columns How can I get all the relevant profiles? -
Django signal m2m_changed does not work with admin
These are my current two models Currently I have two classes class modelStudent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,null=True, blank=True) school = models.ForeignKey(modelSchool) and the other one is class modelPatient(models.Model): student = models.ManyToManyField(modelStudent,null=True,default=None,blank=True) patient_name = models.CharField(max_length=128, unique=False) Now I would like to trigger the following function whenever a new student is assigned. def NewCaseAssigned(sender, **kwargs): if kwargs['action'] not in ('post_add', 'post_clear', 'post_remove'): return inst = kwargs['instance'] I tried using the following signal but that does not work m2m_changed.connect(NewCaseAssigned, sender=modelPatient,dispatch_uid="NewCaseAssigned") However the post_save works post_save.connect(NewCaseAssigned, sender=modelPatient,dispatch_uid="NewCaseAssigned") Any suggestions on how I can fix this issue ? -
prefetch_related using a through tables creating n+1 queries in DEF
I'm having trouble controlling the number of queries my DRF API is calling. I thought to use Prefetch_related to lower the ammount of calls, but still find that the number of calls scales drastically with the number of results, so I have to be doing something wrong. class Role(DirtyFieldsMixin, models.Model): name=models.CharField(max_length=50) class Asset(models.Model): project = models.ForeignKey('self',on_delete=models.CASCADE,null=True) roles = models.ManyToManyField(Role, through='Assignment') properties = JSONField() class Assignment(models.Model): asset = models.ForeignKey(Asset, on_delete=models.CASCADE) role = models.ForeignKey(Role, on_delete=models.CASCADE) users = models.ManyToManyField(User) My serializers look like this: class RoleSerializer(serializers.ModelSerializer): class Meta: model=Role fields=('id','name') class AssignmentSerializer(serializers.ModelSerializer): role=RoleSerializer() class Meta: model=Assignment fields=('id','role','users') class AssetSerializer(serializers.ModelSerializer): roles=AssignmentSerializer(many='Yes',source='assignment_set') @classmethod def setup_eager_loading(cls,queryset): queryset=queryset.prefetch_related( Prefetch('roles',queryset=Assignment.objects.select_related('role'),), ) class Meta: model=Asset fields=('id','project','roles','properties') And my view looks like this: class AssetViewSet(viewsets.ModelViewSet): serializer_class = AssetSerializer filter_backends = (OrderingFilter,DjangoFilterBackend,) filter_class = AssetFilter ordering_fields = 'id' ordering= 'id' def get_queryset(self): queryset=Asset.objects.all() queryset=self.get_serializer_class().setup_eager_loading(queryset) return queryset A call will return a number of results that look like this: (0.000) SELECT `projects_assignment`.`id`, `projects_assignment`.`asset_id`, `projects_assignment`.`role_id` FROM `projects_assignment` WHERE `projects_assignment`.`asset_id` = 2005; args=(2005,) (0.000) SELECT `projects_assignment`.`id`, `projects_assignment`.`asset_id`, `projects_assignment`.`role_id` FROM `projects_assignment` WHERE `projects_assignment`.`asset_id` = 2006; args=(2006,) -
How to know if an assignment is made in django admin - Is that possible?
Currently I have two classes class modelStudent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,null=True, blank=True) school = models.ForeignKey(modelSchool) and the other one is class modelPatient(models.Model): student = models.ManyToManyField(modelStudent,null=True,default=None,blank=True) patient_name = models.CharField(max_length=128, unique=False) Is there a way to know if a modelPatient gets assigned a new student in the admin interface (i.e) a way to know if the many to many field changed ? -
ValueError at / Related model 'Jobs' cannot be resolved Django 1.10
# This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey has `on_delete` set to the desired behavior. # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table=app_labelvalues or field names. from __future__ import unicode_literals from django.db import models class AuthGroup(models.Model): id = models.IntegerField(primary_key=True) # AutoField? name = models.CharField(unique=True, max_length=80, blank=True, null=True) class Meta: managed = False db_table=app_label= 'auth_group' class AuthGroupPermissions(models.Model): id = models.IntegerField(primary_key=True) # AutoField? group = models.ForeignKey(AuthGroup, models.DO_NOTHING) permission = models.ForeignKey('AuthPermission', models.DO_NOTHING) class Meta: managed = False db_table=app_label= 'auth_group_permissions' unique_together = (('group', 'permission'),) class AuthPermission(models.Model): id = models.IntegerField(primary_key=True) # AutoField? name = models.CharField(max_length=255, blank=True, null=True) content_type = models.ForeignKey('DjangoContentType', models.DO_NOTHING) codename = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = False db_table=app_label= 'auth_permission' unique_together = (('content_type', 'codename'),) class AuthUser(models.Model): id = models.IntegerField(primary_key=True) # AutoField? password = models.CharField(max_length=128, blank=True, null=True) last_login = models.DateTimeField(blank=True, null=True) is_superuser = models.BooleanField() username = models.CharField(unique=True, max_length=150, blank=True, null=True) first_name = models.CharField(max_length=30, blank=True, null=True) last_name … -
Django models using API instead of database
I am fairly new to Django and have some requirements that involve creating a Django application to be the front end for an API server. This app should have little need to ever store data in a local database. Instead, we are to access a REST API to get and post data. Being less familiar with the framework, where should I be placing the logic for getting and manipulating data on the remote API? My initial thought was to place this into the models.py file, but models seem to be designed specifically for database access in Django. So then I placed request calls in my form classes's get/post functions. However, this seems like I am mixing up the data logic with the views. Also, I noticed that reloading pages after posting a form would result in the form containing the original GET request for the form until I restarted the server. It appears that I should be placing this logic elsewhere, but I'd like someone to explain what is "standard" in this context. I am sure I not the first person to encounter this and would like some direction on how other projects handle this in Django. Thank you for … -
How to enable hot reloading in mobile devices in the local network? (Django + Webpack-Dev-Server)
Question How do you enable hot reloading of javascript content when using Django and webpack-dev-server? The ideal solution would work even if the local IP-address of the development machine changes. (which happens time to time) Current setup I am running django by python manage.py runserver 0.0.0.0:5555 And I can use a mobile phone in the same wifi to connect to the development server. I get the correct IP-address by import socket local_ip = socket.gethostbyname(socket.gethostname()) print('Developing locally. Access through wifi: {}:5555'.format(local_ip)) Which prints out something like Developing locally. Access through wifi: 192.168.8.105:5555 Using this setup, I can see any HTML content served by django. Then, I added a simple React component, and the django-webpack-loader (v.0.5.0). I am running webpack-dev-server using command "node server.js", with the following "server.js": var webpack = require('webpack') var WebpackDevServer = require('webpack-dev-server') var config = require('./webpack.local.config') var ip = 'localhost' new WebpackDevServer(webpack(config), { publicPath: config.output.publicPath, hot: true, inline: true, host: "1ocalhost", historyApiFallback: true, headers: { "Access-Control-Allow-Origin": "*" } }).listen(3003, ip, function (err, result) { if (err) { console.log(err) } console.log('Listening at ' + ip + ':3003') }) The config.output.publicPath is defined in an another file, and it is config.output.publicPath = 'http://' + ip + ':3003' + '/assets/bundles/'. With … -
Django CSRF Protection with user-based get request
I have the following "profile" view in my django app: @login_required def user_profile(request): current_user = request.user student_profile = get_object_or_404(Student, student_user = current_user) reviews = StudentReview.objects.filter(target_student = student_profile).reverse() for stu_review in reviews: stu_review.review_seen = True stu_review.save() context = { 'user': current_user, 'profile': student_profile, 'reviews': reviews, 'is_logged_in': request.user.is_authenticated, } return render(request, 'polls/profile.html', context) I was wondering whether or not this code is vulnerable to a CSRF attack. Since profile information is sensitive, and since profile information is displayed based on a user's identity, I wasn't sure whether someone could attempt a CSRF attack to display another user's profile information, or whether Django's middleware would take care of that. I have a number of views that behave similarly, so I want to make sure that this information is not at risk. -
Django live preview without reloading the page
I am looking for live preview solution for Django project so as soon as I do change in the css or java-script files I would see these changes without reloading the page in the browser. My page is html page but it has django tags. I tried the following solutions: Atom - livereload plugin. django-livereload 1.7 grunt and others. the Problem with these solutions that as soon I save my page after changes it will reload the whole page to see the chnages. Is there any solution for Django would preview changes without reloading the page and just will preview the changes. I am using django development server to run djange website. I am not looking for inline editor. I am looking for IDE that support live preview for django without reloading the page. -
DRF's CurrentUserDefault isn't returning a user
I have a ModelSerializer. I was trying to set a user foreign key when saving a model, instantiated via the create() and update() methods of a ModelViewSet class. Eg: ModelViewSet: def create(self, request): serializer = self.get_serializer(data=request.data, many=isinstance(request.data, list)) if not serializer.is_valid(): return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) Serializer def process_foreign_keys(self, validated_data): """ Simplified for SO example """ profile = get_object_or_404(Profile, fk_user=CurrentUserDefault()) validated_data['profile'] = profile return validated_data def create(self, validated_data): """ Create a Product instance. Routed from POST via DRF's serializer """ validated_data = self.process_foreign_keys(validated_data) return Product.objects.create(**validated_data) That code doesn't work - it throws an exception on the get_object_or_404 line: int() argument must be a string, a bytes-like object or a number, not 'CurrentUserDefault' If I put a few debugging statements in the ModelSerializer.create() method, I get weird stuff: currentuser = CurrentUserDefault() # Expect <class django.contrib.auth.models.User>, get <class 'rest_framework.fields.CurrentUserDefault'> print("currentuser type " + str(type(currentuser))) # Causes AttributeError: 'CurrentUserDefault' object has no attribute 'user' print("currentuser is " + str(currentuser.__call__())) All this was done while a user was logged in, so it's not an AnonymousUser problem. What am I screwing up? How do I get the current user in a serializer instantiated within the create/update methods of a ModelViewSet via self.get_serializer()? -
Persisting a DataFrame across requests within a Django
I am in the process of re-writing a conceptual Project Management app from Jupyter notebook into a Django app (for context: to be compiled into a windows exe, and accessed over localhost). The main Model is Event which has the usual attributes. However, the Event has a timeseries-indexed DataFrame (~2,000 rows; 50 columns) that can get modified depending on any updates that the user might make during their session. For example: changing the start or end date adding or removing a department (which are columns) Is this something that should/could be added to request.session['myDataFrame']? -
How to display a saved,dynamically created image in django template?
I have created a plot in a view and saved the plot as a png inside the templates folder. But when I try to display this saved image using an <img> tag in a template html file, the image is not displayed. Here is an image of my folder structure: Folder Structure This is how I save my plot inside a view: def result(request): if request.POST and request.FILES: mycsv=pd.read_csv(request.FILES['csv_file']) c=mycsv.X #We divide by the class height(basically) so that Xi+1-Xi=1 x = [d / 5 for d in c] n=len(x) b=mycsv.Y divi=np.sum(b) f = [e / divi for e in b] #Thus sum(f)=1, makes calculation of mean simpler #PLOTTING BEGINS fig = plt.figure() ax = plt.subplot(111) ax.plot(x, f) plt.title('Pearson Type 1 ') ax.legend() #plt.show() fig.savefig('polls/templates/polls/plot.png') context = {'n':n,} return render(request, 'polls/result.html', context) else: return HttpResponse("Form Not Submitted") My result.html file where I try to get the image is: <h1>Graph with {{n}} points</h1> <img src='./plot.png' /> I'm running this on my localhost, is there a problem with permissions? I've just started learning django and wanted to test this thing. Thank you for your help! -
Python - Django - Test Models.save method
Could anyone help me in find a solution to test the Models.save method from Django? What I´m interested here is testing that a Model is beeing saved with all the arguments it needs. It´s a "legacy" database, not managed by django manage.py module class MyModel(models.Model): myname = models.Charfield(max_length=10) created = models.DateTimeField() class Meta: managed = False class MyModelTest(TestCase): def test_create_my_model_instance(self): my_model = Mock(autospec=MyModel) instance = my_model(randomarg=10) instance.save() # here i´d whnt to assert if istance has the # necessary arguments to save to db -
Django PostgreSQL IntegerRangeField and update_or_create
I have a pretty simple model: from django.contrib.postgres.fields import IntegerRangeField from django.db import models class Production(models.Model): title = models.CharField(max_length=100, blank=True, db_index=True) year = models.PositiveSmallIntegerField(blank=True, default=0, db_index=True) index = models.PositiveSmallIntegerField(blank=True, default=0) run_years = IntegerRangeField(blank=True, null=True) But, I'm experiencing a very strange behavior when I'm manipulating my model through update_or_create method. For some reason my IntegerRange field gets just wiped. In [1]: Production.objects.update_or_create(**{'title': '#twentyfiveish', 'year': 2017, 'index': 0, 'run_years': (2017, 2017)})[0].run_years Out[1]: (2017, 2017) In [2]: Production.objects.update_or_create(**{'title': '#twentyfiveish', 'year': 2017, 'index': 0, 'run_years': (2017, 2017)})[0].run_years Out[2]: NumericRange(empty=True) That doesn't look as a desired behavior to me. Is it a bug or not? Please advise. -
Django - how to use reversion
I'm working at my project degree and I need to do an application like a Document Management System. I manage to do something till now but I need also to have version controll for documents(when someone wants to edit a document, first is required to dowload the document,then update it and uploaded as a new version of the existing one) .I read about Django reversion but I did not understand how to integrate it with my app outside admin.My code is available here: https://github.com/rasmim/DMSLic Could someone help me with this? -
AttributeError - object has no attribute 'create'
I'm trying to save a through model which has the following attributes via Django-rest-framework when sending a POST (I'm trying to create a new instance), I get the following error: AttributeError at /api/organisation/provider/ 'EnabledExternalProvider' object has no attribute 'create' any ideas as to what i'm doing incorrectly? the through model in question is: class EnabledExternalProvider(models.Model): provider = models.ForeignKey(ExternalProvider, related_name='associatedProvider') organisation = models.ForeignKey(Organisation, related_name='associatedOrg') enabled = models.BooleanField(default=True) tenantIdentifier = models.CharField('Tenant identifer for organisation', max_length = 128, null=True, blank=True) def __str__(self): return self.provider + '-' + self.organisation my view is: class EnabledExternalProvider(mixins.RetrieveModelMixin, mixins.UpdateModelMixin,generics.GenericAPIView): serializer_class = ConnectedServiceSerializer def get_queryset(self): return EnabledExternalProvider.objects.filter(organisation=self.request.user.organisation_id) def get_object(self): queryset = self.filter_queryset(self.get_queryset()) # make sure to catch 404's below obj = queryset.get(organisation=self.request.user.organisation_id) self.check_object_permissions(self.request, obj) return obj def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) and my serializer is: class ConnectedServiceSerializer(serializers.ModelSerializer): provider=ExternalProviderSerializer(read_only=True) organisation=OrganisationDetailSerializer(read_only=True) class Meta: model = EnabledExternalProvider fields = ( 'organisation', 'enabled', 'tenantIdentifier') read_only_fields = ('organisation', 'provider') I'm POSTing the following: {"provider":"1","tenantIdentifier":"9f0e40fe-3d6d-4172-9015-4298684a9ad2","enabled":true} -
Read input from StdIn when redirecting StdIn to python manage.py shell
I have a python script that I call redirecting it to Django manage.py shell. $ python manage.py shell < script.py I want to take an answer from user to decide what to do. But I can't do it neither with input() or sys.stdin.readline(). With input() answer = input('A question') if answer == 'y': # Do something else: pass Error: EOFError: EOF when reading a line With sys.stdin.readline: answer = sys.stdin.readline('A question') if answer == 'y': # Do something else: pass Error: TypeError: 'str' object cannot be interpreted as an integer What's the correct way for doing that? -
ImportError: No module named vanilla_project.settings.dev
Apache. Django. Forum: http://django-machina.readthedocs.io install with git clone and migrate Why apache dont see settings.dev file ? apache2.conf: WSGIScriptAlias / /var/www/django-machina/example_projects/vanilla/wsgi.py WSGIPythonPath /var/www/django-machina/example_projects <Directory /var/www/django-machina/example_projects> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static/ /var/www/django-machina/example_projects/static/ <Location "/static/"> Options -Indexes </Location> -
Use logging in reusable app
In an open-source Django library I am working on, the logging module is used mainly to notice user for potential errors: import logging logger = logging.getLogger(__name__) def my_wonderful_function(): # ... some code ... if problem_detected: logger.error('Please pay attention, something is wrong...') Most of the time, that's fine. The library works well on Python 2 and Python 3. But today, somebody reported a Python 2 specific error. If the user didn't configure loggers and handlers in its project's settings, he get the following error each time logger.error() is used: No handlers could be found for logger "library.module" The question is: Is there a good way to report errors and warnings to user, but to print nothing (and in particular no error) when the user don't want to configure logging? -
Installing django_auth_ldap / pyldap
Installing Python libraries on my Mac is normally relatively problemless, but with my Windows 10 PC I encounter more headaches. I'd like to setup an LDAP Authentication Backend in Django, and I've already used ldap3 to confirm a bind, with success. I'm now realising that writing a class for my LDAP Backend with just ldap3 is so straightforward, and that installing django_auth_ldap could be another route to explore. Doing a simple "pip install " on my Windows PC results in connection issues, so the following worked with other packages: pip install --trusted-host pipy.python.org <package> This had worked in the past, but it stalls for the django_auth_ldap package, whereby the problem lies when "collecing pyldap". That's where I get a connectiontimeout error. Is there a way to somehow bypass this error, and why can't I install pyldap?