How to access specific index in list in jinja2 - python

Suppose there is list a=[1,2,3,4] in jinja2
and i want to access only 3rd index of list .In other languages we write a[2]
but it shows error in jinja2.
def dashboard(request):
user = request.user
staff_detail = []
staffs = models.Staff.objects.all()
rec_total = models.Recordings.objects.all().count()
rec_enquiry = models.Recordings.objects.filter(type=1).count()
rec_complaint = models.Recordings.objects.filter(type=2).count()
for staff in staffs:
st = dict()
st['staff_detail'] = staff
st['total_recordings'] = staff.recordings_set.all().count()
st['enquiry'] = staff.recordings_set.filter(type=1).count()
st['complaint'] = staff.recordings_set.filter(type=2).count()
staff_detail.append(st)
return render(request, 'hackathon/index.html', {
'staff_detail': staff_detail,
'rec_total': rec_total,
'rec_enquiry': rec_enquiry,
'rec_complaint': rec_complaint,
'staff_first': staff_detail[0],
})
In html file want only the 1st element of staff_detail currently I write
{{staff_detail[0].staff_detail.name}}
but it is showing error
I can only access them using for loop

It should be written as {{staff_detail.0.staff_detail.name}}

Related

django edit and update multiple object of one form

I have one form for add information to table and in craete view I can copy the form as much I want and insert it to the table like this:
My form and can copy them:
But when I want to edit and update them how can I pass the queryset to form and show them in template I write my view like this and choose formset but my formset never show in template:
def machineedit(request, id):
querymachine = machinefixedmodel.objects.get(pk=id)
querywarranty = warranty.objects.get(machine_id=id)
# querygallery = galleryModel.objects.filter(machine_id=id)
querynet = netpriod.objects.filter(machine_id=id)
newadform = modelformset_factory(netpriod, form=netpriodfrom,fields=('activity', 'material'),
extra=0)
# print(newadform)
formmachine = MachinefixedForm(instance=querymachine)
formwaranty = warrantyForm(instance = querywarranty)
# formgallery = galleryform(instance = querygallery)
# formblueprint = galleryform(instance = querygallery)
# formnetpriod = netpriodfrom(instance=querynet)
formnetpriod = newadform(request.POST or None, querynet)
context ={'formmachine': formmachine,
# 'formgallery': formgallery,
'formwarranty': formwaranty,
# 'formblueprint': formblueprint,
'formnetpriod': formnetpriod,}
return render(request, "edit.html", context)
Is the way I choose the right way or not?
can anyone help me please...

How to get multiple queryset from textarea in django

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.

Django data saving and presenting

My Django project need to acquire one list after processing in one function of views.py.
def acquire(request):
import sys
n = []
for topic in Topic.objects.filter(owner=request.user).order_by("date_added"):
entries = topic.entries.all()
q = entries.text
n.append(q)
return render(request, "projects/topics.html", n)
The list "n" above need to be transferred to another function of views.py for the information in another "results.html" page.
def results(request):
data = XXXX
return render(request, "projects/results.html", {"datas": data})
How could I edit "XXX" in results function to transfer the "n" list?
You can write a utility function that can be used by both views and stores the data for the current session:
def acquire(request):
data = _get_data(request)
return render(request, "projects/topics.html", {'data': data})
def results(request):
data = _get_data(request)
return render(request, "projects/results.html", {'data': data})
# this is not a view, but a utility function
def _get_data(request)
# this will try to use the data generated in a previous request of
# the same session. So the data might be stale by now
if not 'user_entries' in request.session:
n = []
for topic in Topic.objects\
.filter(owner=request.user)\
.order_by('date_added')\
.prefetch_related('entries'): # prefetch avoids the nested queries
for entry in topic.entries.all():
n.append(entry.text)
request.session['user_entries'] = n
return request.session['user_entries']
You can declare the list n outside of the function so you can use it wherever you want, like:
n = []
def acquire(request):
import sys
for topic in Topic.objects.filter(owner=request.user).order_by("date_added"):
entries = topic.entries.all()
q = entries.text
n.append(q)
return render(request, "projects/topics.html", n)
def results(request):
data = n
return render(request, "projects/results.html", {"datas": data})
You have to remember that whatever variable you set, it only lives within the view/function as Django is stateless. That's why you have a database and cookies.
This is how you do it. Unless that list has thousands and thousands of entries, this will be fast.
def results(request):
data = []
for topic in Topic.objects.filter(owner=request.user).order_by("date_added"):
entries = topic.entries.all()
q = entries.text
data.append(q)
return render(request, "projects/results.html", {"datas": data})
If you want to be really fast, you could change the request and work on the database level and create a join. Something along the lines of this (I'm a bit rusty)
data = Entries.objects.filter(topic__owner=request.user).order_by("topic__date_added").values("text")

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

Categories