How to pass multiple objects to jinja template using flask:
....
t = t.split(', ')
for i in t:
user = User.query.filter_by(username=i).all()
return render_template('example.html', user=user)
Here renders only one user with last value of 't' list, how to render multiple users based on all values of list 't'?. Thanks.
That is a bad way to query. Making individual querys so many times is bad.
instead us the in_ function. making
t = t.split(', ')
users = []
for i in t:
users.append(User.query.filter_by(username=i).all())
into
User.query.filter(User.username.in_(t)).all()
That returns all the users that have the usernames in the t list
Just pass a list...
....
t = t.split(', ')
users = []
for i in t:
users.append(User.query.filter_by(username=i).all())
return render_template('example.html', users=users)
Related
How can I loop through form data where the ending part could be 1,2,3,4 and so on, and store in the DB without hardcoding the DB like below so each description would be on its own line but one person could post description1-10 and the other 10-27 and so on
for example instead of say this
order.description_1 = request.POST.get('description1')
order.length_1 = request.POST.get('length1')
order.width_1 = request.POST.get('width1')
order.depth_1 = request.POST.get('depth1')
order.weight_1 = request.POST.get('weight1')
order.description_2 = request.POST.get('description2')
order.length_2 = request.POST.get('length2')
order.width_2 = request.POST.get('width2')
order.depth_2 = request.POST.get('depth2')
order.weight_2 = request.POST.get('weight2')
currently the form passes request.POST.get('description1') and with a limit of request.POST.get('description5') but would like each description on its own row and not be subject to a hardlimit and uses a bit of javascript to append the x value to the name. The postdata form is also hardcoded so not using forms.py
The request.POST is a python dictionary, so you can loop through it like this:
for key, value in request.POST.items():
print(key, value)
# set the property for order
# you can work on key and change it if need
setattr(order, key, value)
For a better implementation of this requirement, you can use django forms with ArrayField fields:
django simple array field
how-to-define-arrayfield-to-django-forms
I am trying to "DRY" my code and would like to create a function to make my query dynamic.
The code that I currently use is :
rightone = []
for item in taglist: #taglist is a list of model instances, not relevant here
content = content.filter(tags__title=item.title) #tags here is a M2M key : my problem, content is a query
rightone.append(content)
tagproofquery = rightone[-1]
and I would like to convert it to:
def uniquetogether(queryset,data, model):
rightone = []
for item in queryset:
content = data.filter(tags__title=item.title) # <--- problem is here with tags
rightone.append(content)
tagproofquery = rightone[-1]
return tagproofquery
I have no idea how to replace my M2M "tags" as in tags__title=item.title with the "model" parameter of my function. I tried f strings but it failed miserably (of course).
Is there a way to do this? Many thanks
I sessions up and running and currently I'm getting the variable 'context_number' set in the browser. In the view I would like to filter on this variable. So I have this in my views.py.
def allcontexts(request):
allcontexts = Context.objects.all()
return render(request, 'context_manager/context_manager.html',
{
'allcontexts':allcontexts,
})
In order to filter I change the second row to the following
allcontexts = Context.objects.filter(context_number=____)
In the blank I want to insert the context_number variable, so context_number[dbcolumn] = context_number[session variable]
I can't seem to figure out the correct syntax, any ideas?
You can access session variables using request.session.get() syntax:
allcontexts = Context.objects.filter(context_number=request.session.get("context_number"))
I have a view which should accept an end point with a query parameter, as well as without a parameter.
http://localhost:8001/v1/subjects?owner_ids=62,144
and
http://localhost:8001/v1/subjects
Here's my view file...
class SubjectPagination(JsonApiPageNumberPagination):
"""
Required for frontend to retrieve full list.
"""
max_page_size = 5000
class SubjectViewSet(Subject.get_viewset()):
pagination_class = SubjectPagination
def get_queryset(self):
import pdb; pdb.set_trace()
queryset = Subject.objects.all()
if self.request.GET['owner_ids']:
owner_id_list = self.request.GET['owner_ids'].split(',')
owner_id_list_integer = []
for i in owner_id_list:
owner_id_list_integer.append(int(i))
return queryset.filter(organization__in=owner_id_list_integer)
else:
return queryset
SubjectUserRoleViewSet = Subject.get_by_user_role_viewset(
SubjectViewSet, GroupRoleMap, Role)
I am trying to figure out how to handle both the end points? Please advice what needs to be done at the view to handle a URI with or without query strings?
Here's the urls.py
router.register(r'subjects', views.SubjectViewSet)
First of all, is a good practice to send the parameters in url-form-encode, avoiding things like that, in this case for send a list you could send id as:
?owner_ids[]=62&owner_ids[]=144
the querydict its going to be like this :
<QueryDict: {'owner_ids[]': ['62', '144']}>
and you could process it easily, like this
self.request.GET.getlist('owner_ids[]', [])
remember to use the get and get list functions of the request method GET and POST, to avoid dict errors.
Second, split returns a list the for statement in owner list id is totally unnecessary, and the queryset statement __in accept array of strings, if you actually want to convert all the items to integers use list comprehensions. For example, to convert all the items in a list to integer, just have to use:
owner_ids = [int(i) for i in owner_ids ]
this is way more fast in python and way more pythonic, and also cool too see.
and last, all urls should finish in /, even django has a settings for that called append_slash
this is what i can tell about the ambiguous question you are asking, in the next times please write questions more precisely that help people help you.
I have taken the objects from the tables into 2 variables. Now i want to send the values of those variables to html using render_to_response.
def AssetMovement(request):
print "AssetMovement"
feature_list = request.session['feature_list']
featuresgroups = request.session['featuresgroups']
pplid=request.session['pplid']
empnm = Asset_Assignment_Employee.objects.filter(Employee__People=pplid)
print empnm
id_obj = Asset_Track.objects.all()
print id_obj
report = reports.astmvmt_repo(queryset=id_obj)
report.generate_by(PDFGenerator, filename= 'E:\My Work Location\Example\WorkSpace\\asset_track1\media\\'+str(2)+".pdf")
return render_to_response('asset_mgmt/astmvmtReport.html',{"contacts":feature_list,'root': settings.MEDIA_ROOT,'len':len(feature_list)-1,"featuresgroups":featuresgroups,'assertlist':id_obj})
Like above, I have send id_obj through 'assertlist' now i want to send empnm object with the same name i.e, 'assertlist' and display in the table.
Kindly try to answer this question as soon as possible. Thank You.
Aside from the comments above, another option is to use the {% with %} template tag to re-assign the variable: https://docs.djangoproject.com/en/1.4/ref/templates/builtins/#with