Django Python and pyad

712 Views Asked by At

I am trying to create a simple search form in Django to query Active Directory but I keep getting

com_error at /console/users/
(-2147221008, 'CoInitialize has not been called.', None, None)

views.py:

from pyad import pyad, aduser, adquery

@login_required
def users(request):
    if request.method == 'POST':
        form = UserSearchForm(request.POST)
        if form.is_valid():
            user = pyad.from_cn(form.cleaned_data['cn'])
            return render(request, 'console/users/details.html', {'user': user})
    else:
        form = UserSearchForm()

    return render(request, 'console/users/index.html', {'form': form})

forms.py

from django import forms

class UserSearchForm(forms.Form):
    cn = forms.CharField(label='Common Name', max_length=100)

Python 3.6. Django 2.0.3 pyad 0.5.20

1

There are 1 best solutions below

0
On

You need to Start and end the threading process. See example code below:

@login_required
def users(request):
    import pythoncom   <=== Here
    pythoncom.CoInitialize()   <=== Here
    from pyad import pyad, aduser, adquery 

    if request.method == 'POST':
       form = UserSearchForm(request.POST)
       if form.is_valid():
          user = pyad.from_cn(form.cleaned_data['cn'])
          return render(request, 'console/users/details.html', {'user': user})
    else:
       form = UserSearchForm()

    return render(request, 'console/users/index.html', {'form': form})

    pythoncom.CoUninitialize()    <=== And Here

That should get you to the next step.