I have a view which fetches multiple users from a database based on passed in skills. It works almost as desired except if it returns more than one user it only passes back the most recently fetched user. How do I aggregate fetched users to be passed back to the template. I've tried passing them back as a list but they didn't appear.
Here is my code:
form = FilterFreelancerForm(request.POST)
filtered_skills = set((request.POST.getlist('skills_select')))
match_fl = Freelancer.object.annotate(c=Count('skills')).filter(c=len(filtered_skills))
candidate_freelancers = None
for skill in filtered_skills:
candidate_freelancers = match_fl.filter(skills=skill)
freelancers = None
for freelancer in candidate_freelancers:
freelancers = User.objects.filter(freelancer=freelancer.id)
return render(request, 'freelancestudent/browsefreelancers.html', {'freelancers': freelancers,
'filter_form': form})
I previously had this:
freelancers = []
for freelancer in candidate_freelancers:
freelancers.append(User.objects.filter(freelancer=freelancer.id))
which returns nothing to the template.
Instead of:
for freelancer in candidate_freelancers:
freelancers = User.objects.filter(freelancer=freelancer.id)
try:
freelancers = User.objects.filter(freelancer__in=[freelancer.id for freelancer in candidate_freelancers])
out:
[<User: user1>, <User: user2>]
Related
I'm using django-auth-ldap and I'm trying to get all users from LDAP server, I didn't find a way to do so, the authenticating is working in the backend, here is my code
#api_view(['GET'])
def users(request):
l = ldap.initialize(backend.AUTH_LDAP_SERVER_URI)
l.simple_bind_s(backend.AUTH_LDAP_BIND_DN, backend.AUTH_LDAP_BIND_PASSWORD)
users = LDAPBackend().populate_user('*') #this line is returning None
l.unbind_s()
print (users)
serializer = userSerializer(users, many=True)
return Response(serializer.data)
I know that line is incorrect LDAPBackend().populate_user('*')
but I really need to get all users with something like this : conn.search('ou=users, dc=example,dc=com', '(objectclass=person)', attributes=['uid', 'cn', 'givenName', 'sn', 'gidNumber'])
(this is how I did with another library called ldap3)
Thank you
You can do something like this below
def get_users():
conn = ldap.initialize(LDAP_URL)
results = conn.search_s(GROUP_DN, ldap.SCOPE_ONELEVEL, '(cn=*)')
# get all non-empty uniqueMember of all groups (list of list), flattern the list and get only unique value
users_dn = set(list(chain.from_iterable(filter(lambda x: x, [x[1].get('uniqueMember') for x in results]))))
users = [x.split(',')[0].split('=')[1] for x in users_dn]
return users
I have a text area in which user inputs multiple values in different line and i want to get object for every single line in text area and send it to template. How i should do it.?
if request.method == 'GET':
search = request.GET.get('search')
slist = []
for i in range(4):
slist.append(search.splitlines()[i])
sdata = Stock.objects.all().filter(slug=slist)
return render(request, 'stocks/searchbar.html', {'sdata':sdata})
I'm trying to do it in this way.
You need to do something like this:
sdata = Stock.objects.filter(slug__in=search.splitlines())
Since search.splitlines() returns a list and slug is, I assume, a CharField, you need the in clause in your query.
I'm running into a small problem with writing a unit test for a Django form. I really just want to check the is_valid() method and have seen examples but my code isn't working and after a day or so of reading up on Google I've yet to find the answer I'm looking for. Below is the code for the forms.py and test_forms.py
forms.py
class DataSelectForm(forms.Form):
#these are done in the init funct.
result_type = forms.ChoiceField(widget=forms.Select(attrs={'class': 'field-long'}))
band_selection = forms.MultipleChoiceField(widget=forms.SelectMultiple(attrs={'class': 'multiselect field-long'}))
title = forms.CharField(widget=forms.HiddenInput())
description = forms.CharField(widget=forms.HiddenInput())
def __init__(self, result_list=None, band_list=None, *args, **kwargs):
super(DataSelectForm, self).__init__(*args, **kwargs)
if result_list is not None and band_list is not None:
self.fields["result_type"] = forms.ChoiceField(choices=result_list, widget=forms.Select(attrs={'class': 'field-long'}))
self.fields["band_selection"] = forms.MultipleChoiceField(widget=forms.SelectMultiple(attrs={'class': 'multiselect field-long'}), choices=band_list
test_forms.py
def test_data_select_form(self):
results = ResultType.objects.all()
results_value = []
for result in results:
results_value.append(result.result_type)
bands = SatelliteBand.objects.all()
bands_value = []
for band in bands:
bands_value.append(band.band_name)
form_data = {'result_type': results_value, 'band_selection': bands_value, 'title': 'a title', 'description': 'some description'}
form = DataSelectForm(data = form_data)
print(form['title'].value())
print(form['description'].value())
print(form['result_type'].value())
print(form['band_selection'].value())
self.assertTrue(form.is_valid())
The only thing I get when I run the test case is "AssertionError: False is not true" I understand the error, just not why I'm getting it. I'm passing in all the data and I can see it when I run the print statements. I've tried taking the result_type and band_selection and passing it into the constructor instead of it being a part of the form_data but that didn't work either. What am I missing?
You need to pass result_list and band_list when you construct your form.
# These aren't the actual choices you want, I'm just showing that
# choices should be a list of 2-tuples.
result_list = [('result1', 'result1'), ('result2', 'result2'), ...]
band_list = [('band1', 'band1'), ('band2', 'band2'), ...]
DataSelectForm(result_list=result_list, band_list=band_list, data=form_data)
If you don't pass the values to the form, then you don't set the choices for the fields. If the fields don't have any choices, then the values in the data dict cannot be valid, so the form will always be invalid.
Hi I'm trying to get the value from request.args(0) and use it in the submitting of a form.
I want 'game_id' to be automatically assigned the args value (which is the unique ID of the game in my games table.
def review():
getId = db.games(request.args(0)) or redirect(URL('default', 'index'))
formReview = SQLFORM(db.reviews,fields = ['game_id','title','review']).process()
db.reviews.game_id.default= request.args(0)
formReview.vars.game_id = request.args(0)
if formReview.accepted: redirect(URL('index'))
return dict(formReview=formReview, getId=getId)
db.define_table('reviews',
Field('title',requires=IS_NOT_EMPTY()),
Field('review','text',requires=IS_NOT_EMPTY()),
Field('game_id', 'reference games'))
I thought the line:
formReview.vars.game_id = request.args(0)
would pre populate the field but it isn't working.
The most reliable way to pre-populate the form is by setting the field's default value (which must be done before creating the form):
def review():
getId = db.games(request.args(0)) or redirect(URL('default', 'index'))
db.reviews.game_id.default = request.args(0)
formReview = SQLFORM(db.reviews, fields=['game_id','title','review']).process()
if formReview.accepted: redirect(URL('index'))
return dict(formReview=formReview, getId=getId)
I'm trying to build a search system, and I want to search by multiple fieldsname, state, city, in my django models. I wrote the below code, yet I've been unable to figure out how to go about it. I use Q but it seems not working:
views.py:
def data_consulting(request):
if request.method == 'POST':
form = FilterForm(request.POST)
if form.is_valid():
conditions = [('toBuy', form.cleaned_data['toBuy']), ('name__contains', form.cleaned_data['searchName']),(('price__gte', form.cleaned_data['searchPriceBegin']), ('price__lte',form.cleaned_data['searchPriceEnd'])),(('calories__gte', form.cleaned_data['searchCalorieBegin']), ('calories__lte', form.cleaned_data['searchCalorieEnd'])), (('date__gte',form.cleaned_data['DateBegin']), ('date__lte', form.cleaned_data['DateEnd']))]
all_products = Product.objects.filter(reduce(operator.or_, [Q(condition) for condition in conditions]))
send = True
all_products = Product.objects.filter(reduce(operator.or_, [Q(condition) for condition in conditions]))
else:
form = FilterForm()
all_products = Product.objects.all()
return render(request, 'mealManager/data_consulting.html', locals())
Have a think about what
reduce(operator.or_, [Q(condition) for condition in conditions])
becomes with e.g. [('toBuy', 'bread'), ('name__contains', 'bread')]. It becomes
Q(('toBuy', 'bread')) | Q(('name_contains', 'bread'))
which is obviously wrong syntax, since Q rather needs kwargs than a tuple:
Q(toBuy='bread') | Q(name__contains='bread')
that's where the ** operator comes to the rescue. If you get data like this:
[{'toBuy': 'bread'}, {'name__contains': 'bread'}]
which may be accomplished by simply changing the conditions assignment you can then do
reduce(operator.or_, [Q(**condition) for condition in conditions])
which translates in the particular case to
Q(toBuy='bread') | Q(name__contains='bread')
which is exactly what we need.