How to get multiple queryset from textarea in django - python

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.

Related

Getting all LDAP users with django

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

django-rest-framework : list parameters in URL

I am pretty new to django and django-rest-framework, but I am trying to pass lists into url parameters to then filter my models by them.
Lets say the client application is sending a request that looks something like this...
url: "api.com/?something=string,string2,string3&?subthings=sub,sub2,sub3&?year=2014,2015,2016/"
I want to pass in those parameters "things", "subthings", and "years" with their values.
Where the url looks something like this?
NOTE: Trick is that it won't be always an array of length 3 for each parameter.
Can someone point me in the right direction for how my url regex should be handing the lists and also retrieving the query lists in my views.
Thanks!
To show how I did this thanks to the document links above.
Note: I used pipes as my url delimiter and not commas -> '|'.
in my urls.py
url(r'^$', SomethingAPIView.as_view(), name='something'),
in my views.py
class SomethingAPIView(ListAPIView):
# whatever serializer class
def get_queryset(self):
query_params = self.request.query_params
somethings = query_params.get('something', None)
subthings = query_params.get('subthing', None)
years = query_params.get('year', None)
# create an empty list for parameters to be filters by
somethingParams = []
subthingsParams = []
yearParams = []
# create the list based on the query parameters
if somethings is not None:
for something in somethings.split('|'):
countryParams.append(int(something))
if subthings is not None:
for subthing in subthings.split('|'):
subthingsParams.append(int(subthing))
if years is not None:
for year in years.split('|'):
yearParams.append(int(year))
if somethings and subthings and years is not None:
queryset_list = Model.objects.all()
queryset_list = queryset_list.filter(something_id__in=countryParams)
queryset_list = queryset_list.filter(subthing_id__in=subthingsParams)
queryset_list = queryset_list.filter(year__in=yearParams)
return queryset_list
I do need to check for an empty result if they are not valid. But here is starting point for people looking to pass in multiple values in query parameters.
A valid url here would be /?something=1|2|3&subthing=4|5|6&year=2015|2016.
Checkout this doc http://www.django-rest-framework.org/api-guide/filtering/
Query params are normally not validated by url regex

Django Formsets: How to properly iterate over forms in a formset and save the corresponding dictionaries

I have created a formset and I know that form data is being returned as a dictionary. I thought that I could just loop over the forms in a formset and store every dictionary in another dictionary. That doesn't seem to work though, because I am only able to store the latest form (in my template I can dynamically add and remove forms). What I tried was this:
def index(request):
data = {}
data['education_data'] = {}
EducationFormSet = formset_factory(EducationForm)
if request.method == "POST":
persoform = PersonalForm(request.POST)
education_formset = EducationFormSet(request.POST)
if persoform.is_valid() and education_formset.is_valid():
data['personal_data'] = persoform.cleaned_data
entry = 1
en = 'entry_%d' % entry
for form in education_formset:
data['education_data'][en] = form.cleaned_data
entry = entry + 1
print(data)
My wanted output would be:
data = {'personal_data':{inputs}, 'education_data': { 'entry_1':{inputs}, ... 'entry_n':{inputs}}}
EDIT:
The problem was the way I tried to add keys to the "Education_Data" key. The following works:
for form in education_formset:
data['education_data']['entry_%d' % entry] = form.cleaned_data
[...]

Returning multiple fetched users

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>]

search multiple fields django

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.

Categories