Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJANGO password reset link
Hey , please i want to send an email with custom reset link in django in case the user click the reset button in the login page. **ps :** iam hosting my app on aws and i'm using my email to send . -
How to use django-autocomplete-light on django-countries==7.1 country fields for admin panel
I want the To country field for the admin field as per My Model.py File. how to use it. settings.py file:- INSTALLED_APPS = [ 'dal', 'dal_select2', # 'grappelli', 'widget_tweaks', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'admission', 'employment', 'form', 'frontend', 'study', 'travel', 'hrm', 'event', 'dal_queryset_sequence', ] Model.py file:- from django.db import models from django_countries.fields import CountryField class University (models.Model): ESTABLISHED_YEAR_CHOICES = [(x, str(x)) for x in range(1088, 2021, 1)] university_logo = models.ImageField(upload_to='pics', verbose_name="University Logo") university_name = models.CharField(max_length=255, verbose_name="Name") university_rank = models.IntegerField(verbose_name="Rank", default="0") university_country = CountryField() international_students = models.IntegerField( blank=True, null=True, verbose_name="International Students") established_year = models.IntegerField( choices=ESTABLISHED_YEAR_CHOICES, blank=True, null=True, verbose_name="Established Year") total_students = models.IntegerField(blank=True, null=True, verbose_name="University Total Student") university_website= models.CharField(max_length=255, blank=True, null=True, default="https://www", verbose_name="University Website") university_address= models.CharField(max_length=255, blank=True, null=True, verbose_name="University Address") def __str__(self): return self.university_name class Meta: verbose_name = 'Top University' verbose_name_plural = 'Top Universitys' -
Error: [Win Error 10049] The requested address is not valid in its context
I am new to using Nginx. I am trying to host my Django application on Ngnix so that I can expose APIs defined in views.py so that they are accessible from other server. But I am getting above error while starting Django application. site specific .conf file: server { listen 8004; charset utf-8; client_max_body_size 10M; location / { proxy_pass http://10.11.12.34 } } nginx.conf file: worker_processes 10; error_log logs/error.log; events { worker connections 1024; } http { include mime.types; include '../../.conf' #included path to site-specific .conf file access_log logs/access.log; sendfile on; keepalive_timeout 65; } Added new file Django runserver.py: (code snippet) if __name__ == '__main__': serve(application, host = 10.11.12.34, port 8004) What must be causing this error? Also, I am not sure what IP address to be used there? how to decide which IP address to be configured? Can someone help me with this? -
MultipleObjectsReturned at /ordered-list/
Please help to solve this problem. I have an issue with MultipleObjectsReturned at / ordered-list / get() returned more than one Order -- it returned 2! This is the problem I want to display all the items in the database based on the field "disiapkan"=False order = Order.objects.get(user=self.request.user, disiapkan=False) View.py class OrderedListView(LoginRequiredMixin, View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, disiapkan=False) context = { 'order' : order } return render(self.request, 'ordered_list.html', context) except ObjectDoesNotExist: return redirect('beranda') models.py class Order(models.Model): id_order = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) address = models.ForeignKey("Address", on_delete=models.SET_NULL, blank=True, null=True) payment = models.ForeignKey("Payment", on_delete=models.SET_NULL, blank=True, null=True) coupon = models.ForeignKey("Coupon", on_delete=models.SET_NULL, blank=True, null=True) ordered = models.BooleanField(default=False) disiapkan = models.BooleanField(default=False) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() def __str__(self): return self.user.username def get_total(self): total = 0 for order_item in self.items.all(): total += order_item.get_final_price() return total def get_total_after_coupon(self): total = 0 for order_item in self.items.all(): total += order_item.get_final_price() if self.coupon: total -= self.coupon.amount return total urls.py from django.urls import path from .views import ( HomeView, CheckoutView, ProductDetail, add_to_cart, add_to_cart2, PaymentView, CouponView, remove_from_cart, OrderSummaryView, remove_perUnit_from_cart, ordersummary2, OrderedListView, OrderedListDikirimView, OrderedListDiterimaView, remove_coupon, ) urlpatterns = [ path('beranda', HomeView.as_view(), name='beranda'), path('checkout/', CheckoutView.as_view(), name='checkout'), path('add-coupon', CouponView.as_view(), name='add_coupon'), path('payment/<payment_option>/', PaymentView.as_view(), name='payment'), path('product/<slug>/', ProductDetail.as_view(), name='product'), … -
Get the values of a Polymorphic model and pass it to different serializers
ModelA(PolymorphicModel) ModelB(ModelA) ModelC(ModelA) ModelD(BaseModel) items = models.ManyToManyField(ModelA) def get_items(self): return self.items.all() Now I have to get the list of all the models under the polymorphic through ModelD. serializers.py class ModelDSerializer(serializers.ModelSerializer): items = serializers.SerializerMethodField() class Meta: model = models.ModelD fields = "__all__" def get_items(self, obj): // obj.get_items() Now I have to pass the items to the different serializers. Like, if the item is a ModelB, then I will pass it to ModelBSerializer. If it is a ModelC I will send it to ModelBSerializer. How can I execute this? -
Raising a ValidationError of a Date in Django
I want to raise a validation error in my form. If date is invalid, raise my own message instead of Django's default message. Here is my form.: def clean_birth_date(self, *args, **kwargs): birth_date = self.cleaned_data.get("birth_date") date_valid = False birth_date = str(birth_date) year = birth_date[0:4] month = birth_date[5:7] day = birth_date[8:10] # Check if birth_date is a proper date birth_date = year.zfill(4) + month.zfill(2) + day.zfill(2) print("TEST") try: birth_date = datetime.strptime(birth_date, '%Y%m%d') date_valid = True except ValueError: date_valid = False if not date_valid: print("TEST") raise forms.ValidationError("Something Message Here.") return birth_date If the date is valid, I can see the TEST in my terminal. That means my clean function works(I think). However, if invalid like 123, or Feb 30, I can't see the TEST in terminal and django returns its default message. If you have an idea, please let me know. -
How can I fix styles.css:1 Failed to load resource: the server responded with a status of 404?
i am trying to learn django and my css file cant be linked with the html file idk why ├── images ├── js ├── plugins └── styles └── styles.css This is the tree of the static folder STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, 'static') ] settings.py file ^^ <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>BMI Calculator</title> {% load static %} <link rel="stylesheet" href="{% static './styles/styles.css' %}"> </head> <!-- <script src="../data/script-clac.js" type="text/javascript"></script> --> <body class="body1"> <div class="div1"> <h2>BMI Calculator</h2> <p class="text">Name</p> <input type="text" placeholder="Enter your name" id="name"> <p class="text">Username</p> <input type="text" placeholder="Choose a username" id="username"> <p class="text">Password</p> <input type="password" placeholder="Choose a password" id="password"> <p id="result"></p> <input type="checkbox" onclick="myFunction()">Show Password <button id="btn" onClick="BMI()">Calculate</button> </div> </body> </html> index.html file styles.css:1 Failed to load resource: the server responded with a status of 404 (Not Found) Error in the page console I have been trying to fix the problem since a long time, please help me. -
(1048, "Column 'brand_id' cannot be null") in django rest framework
I am trying to create an api where a user can add their products. I am sending raw json data from postman but it is giving this error. IntegrityError at /api/addproducts (1048, "Column 'brand_id' cannot be null") I am sending brand id in the data. I am not sure what is happening. Here I am sending merchant_id as well as categories ids but why brand field is creating an error I am not sure. My models: class Category(models.Model): name = models.CharField(max_length=100, unique=True) image = models.ImageField(null=True, blank=True) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.name class Brand(models.Model): brand_category = models.ForeignKey(Category,on_delete=models.CASCADE,blank=True,null=True) name = models.CharField(max_length=100, unique=True) image = models.ImageField(null=True, blank=True) class Meta: verbose_name_plural = "Brands" def __str__(self): return self.name class Collection(models.Model): name = models.CharField(max_length=100, unique=True) image = models.ImageField(null=True, blank=True) class Meta: verbose_name_plural = "Collections" def __str__(self): return self.name class Variants(models.Model): SIZE = ( ('not applicable', 'not applicable',), ('S', 'Small',), ('M', 'Medium',), ('L', 'Large',), ('XL', 'Extra Large',), ) AVAILABILITY = ( ('available', 'Available',), ('not_available', 'Not Available',), ) product_id = models.CharField(max_length=70,default='OAXWRTZ_12C',blank=True) price = models.DecimalField(decimal_places=2, max_digits=20,default=500) size = models.CharField(max_length=50, choices=SIZE, default='not applicable',blank=True,null=True) color = models.CharField(max_length=70, default="not applicable",blank=True,null=True) variant_image = models.ImageField(upload_to="products/images", blank=True) thumbnail = ImageSpecField(source='variant_image', processors=[ResizeToFill(100, 50)], format='JPEG', options={'quality': 60}) quantity = models.IntegerField(default=10,blank=True,null=True) # available quantity … -
How to show the progress bar when submitting the form in javascript-ajax
I have already made the brogress bar and everything. But I have problem when I choose the file the file is upload, that's mean the file is uploading twice, once when choosing the file and one once submit the form, and this bad user experince so I wan't show the brogress bar only when submmit the form, I using Django in backend and ajax recall my html form <div id="alert-box"></div> <form id="upload-form" action="." method="post" enctype="multipart/form-data"> {% csrf_token %} <div id="progress-box" class="d-none">progress</div> <div class="custom-file"> <input type="file" class="custom-file-input" id="formGroupExampleInput2" required value="{{V_form.video}}"> <label class="custom-file-label" for="formGroupExampleInput2">Choose Video...</label> </div> <div class="custom-file mt-5 mb-4"> <input type="file" class="custom-file-input" id="file2" required value="{{V_form.video_poster}}"> <label class="custom-file-label" for="formGroupExampleInput2">Choose Poster For Your Video...</label> </div> <div class="d-flex justify-content-center my-3 px-3" > <button class="btn-block btnn-color" id="heel" name="submit_v_form"> Upload</button></div> </form> the javacript-Ajax const file_input_label = document.getElementById('file_input_label') function input_filename(){ file_input_label.innerHTML = input.files[0].name; console.log(file_input_label); } const uploadForm = document.getElementById('upload-form') // const input = document.getElementById('formGroupExampleInput2') const input = document.getElementById('formGroupExampleInput2') console.log(input) const alertBox = document.getElementById('alert-box') const imageBox = document.getElementById('image-box') const progressBox = document.getElementById('progress-box') const canceleBox = document.getElementById('cancel-box') const canceleBtn = document.getElementById('cancel-btn') const csrf = document.getElementsByName('csrfmiddlewaretoken') // whenever choose th file something happen input.addEventListener('change', ()=>{ progressBox.classList.remove('d-none') canceleBox.classList.remove('d-none') var filePath = input.value; var allowedTypes = /(\.mp4|\.mkv|\.avi|\.flv)$/i; if(!allowedTypes.exec(filePath)){ alertBox.innerHTML = `<div class="alert … -
TypeError: metaclass conflict: the metaclass of a derived class
from rest_framework import serializers from rest_framework.serializers import ModelSerializer from .models import Product class ProductSerializer(serializers, ModelSerializer): class Meta: model = Product fields = '__all__' -
How can I get django to work on https using elastic beanstalk and apache?
I have my .config files set up using the information available on aws and I have my load balancer listening on 443. My website is being served correctly via https when I connect using my elastic beanstalk url. Of course that url is not what my ssl certificate lists so there's an error but none the less, it is displaying all the html and static files. Https seems to be working there. When I attempt to visit my custom domain using http everything also displays correctly so my application seems fine, but when I attempt https using my custom domain nothing is loaded from my server. I just get the "Index of /" page. This is what I receive when my ALLOWED_HOSTS is incorrect so I assume it's something super simple in my settings file that is blocking django from allowing apache to serve the content over https to my custom domain. Or else theres one other place I'm missing that needs me to register my domain with my load balancer? Is that a thing? I feel like I've been scouring the internet for help here so any suggestions are very much appreciated. One other note is that I have … -
How to add Dyanmic Numpy Array field in Django Models
I wanted to add the numpy array as a field of my Django models using Django's default db.sqlite database. The "ArrayField" is not available with db.sqlite. Is there any option . Please Answer! -
Does queryset.values_list makes another call to db?
Let's say I have an already evaluated queryset. # queryset is evaluated here queryset = MyModel.objects.filter(name="blabla") for obj in queryset: # do some stuff if I call .values_list on this queryset later on, does it make an extra call to the database or fetch the response from the queryset object cache? obj_map = {k: v in queryset.values_list("id", "name")} # <- does it make a call? -
Django: Ajax Call Returning Expected Values, Not Entering Success
I have three ajax calls in an input form. All three operate in the same way. User clicks submit button, and URL params are passed to a function in views.py. The function is executing as expected and returning the values to the route in the Ajax call. When I visit the specific route with params route/cust-search?name=example&filter_by=example, I can see my data. The last stage uses the success function to grab the data from the route and load it into the pages' layout. My other two calls work and are set up in the exact same way. Why is this call not entering success? <script> $(document).on('submit','#cust_search',function(e){ e.preventDefault(); e.stopPropagation(); $.ajax({ type:'GET', url:'cust-search/', data:{name:$('#gc-input_name_search').val(), filter_by:$('#gc-input_filter_by').val(),}, success:function update_items(){ $('.search-results_table_body').html('').load( "{% url 'CustSearch' %}?name=" + $('#gc-input_name_search').val() + "&filter_by=" + $('#gc-input_filter_by').val()); }, error: function(){} }); e.stopImmediatePropagation(); return false; }) </script> -
Django: how to do unit test in updating views and models for web functionality
I am a testing learner and I have been learning to do unit test for a web project with django views and models. I am taking one of the perspect I want to test on as a learning example, which is a updating functionality of the website. class Tradie(models.Model): myUser = models.OneToOneField(MyUser, on_delete=models.CASCADE, primary_key=True) joinDate = models.DateField(auto_now_add=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) gender = models.CharField( null=False, max_length=10, choices=[(_type.name, _type.value) for _type in GenderChoice], default='Male', blank=True ) description = models.CharField(max_length=200, blank=True) phone = models.CharField(max_length=10, blank=True) address1 = models.CharField(max_length=100, blank=True) address2 = models.CharField(max_length=100, blank=True, null=True) suburb = models.CharField(max_length=30, blank=True) state = models.CharField( null=False, max_length=10, choices=[(_type.name, _type.value) for _type in States], default='ACT', blank=False ) postcode = models.CharField(max_length=5, blank=True) and the corresponding tradie profile based on the class is as seen. def tradie_profile(request): if request.user.is_authenticated: try: tradie = Tradie.objects.get(myUser=request.user) except Tradie.DoesNotExist: raise Http404("Tradie does not exist") context = { "login_status": json.dumps(True), "description": tradie.description, "fullname": tradie.first_name + " " + tradie.last_name, "address": str(tradie.address1 + " " + tradie.suburb + " " + tradie.state + " " + tradie.postcode), "phone": tradie.phone, } return render(request, "Tradie/tradie_profile.html", context) else: raise Http404("Haven't logged in") and the corresponding update function for updating the profile is as seen. def update_tradie_profile(request): … -
GET http://localhost:8000/manifest.json 404 (Not Found) ERROR on django with react
I am currently learning React.js and started to combine it with django. I tried to build a simple homepage that will display Hello World! import logo from './logo.svg'; import './App.css'; import React from 'react'; import ReactDOM from 'react-dom'; class App extends React.Component{ render(){ return ( <h1>Hello World!</h1> ) } } export default App; It works fine on the browser, but when I checked the console, there is an error GET http://localhost:8000/manifest.json 404 (Not Found). What is this manifest.json file that I am missing? This is how I set up my django project settings: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'frontend/build/static')] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'frontend/build')], ... ... ], }, }, ] My project tree looks like this: And the error looks like this: Any idea on what to do with this error? -
How to Update Multiple Image using generic view (UpdateView)
VIEWS.PY This is UpdateView where should I put the exact but maybe I'm wrong. The Image.objects.create is a model connected to Post Model. And the image is located to forms.py but I can't get all save files when i'm trying to click update for this multiple images. class UpdatePostView(LoginRequiredMixin,UserPassesTestMixin, UpdateView): model = Post form_class = PostForm template_name = "Dashboard/edit-post.html" def form_valid(self, form): form.instance.author = self.request.user p = form.save() images = self.request.FILES.getlist("image") for i in images: Image.objects.create(post=p, image=i) return super().form_valid(form) FORMS.PY -This is the forms where I put multiple Image "Image" for posting more images class PostForm(forms.ModelForm): image = forms.FileField(required=False, widget=forms.FileInput(attrs={ "class":"form-control", "multiple":True })) class Meta: model = Post fields = ('title','featured_image','content', 'category','tag','previous_post','next_post' ) -
Django can't display data from two models
I am trying to display data from two different models. The two models have a one-to-many relationship but I am not sure why it is not displaying the data from the MembersPresent model. Here are my models and view class fly_minute(models.Model): mode = ( ('Email', 'Email'), ('Zoom', 'Zoom'), ('Alternative', 'Alternative'), ) mode_of_meeting = models.CharField(max_length=100, choices=mode, blank=False, ) date = models.DateField() Time = models.TimeField() minute_prepared_by = models.CharField(max_length=25) location = models.CharField(max_length=25) authorize_by = models.CharField(max_length=25) item = models.TextField() owner = models.CharField(max_length=25) def __str__(self): return self.mode_of_meeting class MembersPresent(models.Model): flyminute = models.ForeignKey(fly_minute, on_delete=models.CASCADE) name = models.CharField(max_length=25) status = models.CharField(max_length=25) email = models.EmailField(max_length=25) phone = models.IntegerField() def __str__(self): return self.name @login_required(login_url='login_page') def MinutesReport(request, minute_id): report = fly_minute.objects.filter(id=minute_id) return render(request, 'minute_report.html', locals()) {%for rpt in report%} <tbody> <tr class="table-active"> <td>{{rpt.flyminute.name}}</td> <td>{{rpt.flyminute.status}}</td> <td>{{rpt.flyminute.email}}</td> <td>{{rpt.flyminute.phone}}</td> </tbody> {%endfor%} -
Django DefaultRouter and ViewSets question
I've this route: router.register(r'posts/(?P<post_id>\d+)/comments', views.CommentViewSet) How do i get post_id in CommentViewSet class? -
user_passes_test for models other than User in Django
I want to allow a user to edit a project page if ifAdmin (an object in uProject model) == True. I am currently trying to use @user_passes_test to render a view to update the project, but am having difficulties. Here's my code. def admin_check(uProjects): return uProjects.ifAdmin = True @user_passes_test(admin_check) def update(request): etc, etc, etc Please let me know what I can do instead. Thanks in advance@ -
(Django) Making Custom on_delete & CASCADE functions
There is a legacy codebase and its deletion system has to be changed to soft-deletion. I made an additional field in each model like so: is_deleted = models.BooleanField(default=False) and in the utils.py file, I have defined some functions to utilize the is_deleted field . . . def card_related_objs_soft_cascade(instance): print("initiating 'card_related_objs_soft_cascade'...") with transaction.atomic(): with suppress(ObjectDoesNotExist): instance.order.soft_delete() instance.invoices.all().qs_soft_delete() instance.payments.all().qs_soft_delete() def account_related_objs_soft_cascade(instance): print("initiating 'account_related_objs_soft_cascade'...") with transaction.atomic(): instance.contacts.all().qs_soft_delete() instance.meeting_notes.all().qs_soft_delete() instance.attachment.all().qs_soft_delete() class ReusableModelMethods: def soft_delete(self): with transaction.atomic(): print(f"initiating 'soft_delete' on {self.__class__.__name__} instance") ops = { "Board": board_related_objs_soft_cascade, "CardList": cardlist_related_objs_soft_cascade, "Card": card_related_objs_soft_cascade, "Customer": account_related_objs_soft_cascade, "Supplier": account_related_objs_soft_cascade, } self.is_deleted = True self.save() ops.get(self.__class__.__name__, lambda *args: None)(self) class ReusableQuerySetMethods(models.query.QuerySet): @classmethod def as_manager(cls): manager = SoftDeleteManager.from_queryset(cls)() manager._built_with_as_manager = True return manager def qs_soft_delete(self, *args, **kwargs): print("initiating 'qs_soft_delete'...") for instance in self: instance.soft_delete() self._result_cache = None qs_soft_delete.alters_data = True However, when you look at this, there is a lot to maintain as the codebase expands. For instance, in def account_related_objs_soft_cascade(instance), there are three models (contacts, meeting_notes, attachment) related to this account model. As we add more models, I must add more of instance.some_model_set.all().qs_soft_delete() and the chance is, I would forget to do this... And thus, I would like to implement something that does this automatically, hence I looked at CASCADE … -
Modifing one off many post with JS and Django?
so I am currently working on CS50 network project for and I am stuck in to edit a post upon many post that are displayed. I have a view that displays all the post done by a user. def profile(request, username): if request.method == "GET": user = User.objects.filter(username=username) profile = Profile.objects.filter(user=user[0]).get() posts = Post.objects.filter(user=user[0]).order_by('-publish_date') return render( request, 'network/profile.html', { 'posts': page, 'profile': profile, } ) And it is displayed in and html template. {% for post in posts %} <div class="card text-center"> <div class="card-header"> <a href="{% url 'profile' post.user %}"> {{ post.user }} </a> </div> <div class="card-body"> <h5 class="card-title">{{ post.content }}</h5> <p class="card-text">{{ post.num_likes }}</p> <a href="#" class="btn btn-primary" onclick="editpost()"> Edit </a> </div> <div class="card-footer text-muted"> {{ post.publish_date }} </div> </div> <br> {% endfor %} I understand that I need to have a function that with JS changes the tag and tag from with in that specific form but I know how to get it form only that one post and not from all of the post that are being produced by Djangos templating engine. Once I can select them I will copy there information into a var and change the style so the display in non as well as … -
Django Channel stuck for a while
currently I am having some problems with the Django channel. I have been developed a web application to receive data from GNSS and display its position as a machine in the frontend. So I have used the Django channel to connect and received data from GNSS. After we connected to GNSS, around 15 to 17 seconds, we can process data inside the Django channel and return its position into the frontend but after the next 17 seconds, data are still receiving in the Django channel but it stops return data to the frontend to display and when I disconnected real GNSS from the system, those data after 17 seconds are starting processing again. Does anyone know how to solve this? Thank you -
Django django.db.utils.OperationalError in test after adding signals
My test files works perfectly fine but after adding signal getting django.db.utils.OperationalError: no such table: contacts_modellog What acctually happened my signal is not using migarations or other? Here is the signal code. IGNORE_LIST = ['ModelLog'] @receiver(post_save) def post_save_signal(sender, created, **kwargs): if created and sender.__name__ not in IGNORE_LIST: ModelLog.objects.create(model_name=sender.__name__, action='Created') elif sender.__name__ not in IGNORE_LIST: ModelLog.objects.create(model_name=sender.__name__, action='Edited') full traceback Creating test database for alias 'default'... Traceback (most recent call last): File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: contacts_modellog The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/commands/test.py", line 23, in run_from_argv super().run_from_argv(argv) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/commands/test.py", line 53, in handle failures = test_runner.run_tests(test_labels) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/test/runner.py", line 684, in run_tests old_config = self.setup_databases(aliases=databases) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/test/runner.py", line 604, in setup_databases return _setup_databases( File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/test/utils.py", line 169, in setup_databases connection.creation.create_test_db( File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/db/backends/base/creation.py", line 67, in … -
LDAPInvalidServerError at /login/ No exception message supplied
I used Python3 in windows 10 to write a django2 web app. I tried to configure the LDAP login, but failed. When I test using postman to test, it could get the reply successfully. That is, I send a request to https://example.com/staff, with some authentication code and payload containing username and password, and it reply me with the LDAP reply. However, when I tried to using ldap3 in Django, seems like Django ldap3 requires a ldap server address and port, a web address containing LDAP API could not work. class LDAPBackend: def authenticate(self, request, username=None, password=None, **kwargs): now = datetime.datetime.now() text = str(now.day) + 'ls@bBk3y' def computeMD5hash(my_string): m = hashlib.md5() m.update(my_string.encode('utf-8')) return m.hexdigest() # set username to lowercase for consistency username = username.lower() # get the bind client to resolve DN logger.info('authenticating %s' % username) # set your server server = Server("https://example.com/staff") try: print("begin connect!") conn = Connection(server, user=username, password=password, auto_bind=True,) conn.open() conn.bind() print("connected") except LDAPBindError as e: logger.info('LDAP authentication failed') logger.info(e) return None user = UserModel.objects.update_or_create(username=username) return user def get_user(self, user_id): try: return UserModel._default_manager.get(pk=user_id) except UserModel.DoesNotExist: return None always show this: LDAPInvalidServerError at /login/ No exception message supplied