if same id is present in two tables show edit button else show assign button in django - django-models

Get all the employee profile table id and check the id with employee process,if id matches show edit button in templates else show assign button.
Views.py
def Employee(request):
emp = Emp_Profile.objects.filter(is_active=True)
emptable = Emp_Profile.objects.values_list('id')
print(emptable)
empprocess = Emp_Process.objects.values_list('username_id').distinct()
print(empprocess)
obj = {}
for i in range(len(empprocess)):
obj[i] = empprocess[i]
return render(request, 'employee.html',{'list' : emp,'empprocess':empprocess,'obj':obj})
templates
{% for list in list %}
{% if obj != list.id %}
<td>
<a href="/view_client_process/{{ list.id }}"><button
class="btn btn-info">Edit</button></a>
</td>
{% else %}
<h6>welcome</h6>
<td>
<a href="/view_client_process/{{ list.id }}"><button
class="btn btn-info">Assign</button></a>
</td>
{% endif %}
{% endfor %}

You can construct a set of username_ids and pass this to your template:
def Employee(request):
empS = Emp_Profile.objects.filter(is_active=True)
empprocess = set(Emp_Process.objects.values_list('username_id', flat=True).distinct())
return render(request, 'employee.html', {'emps' : emps, 'empprocess': empprocess })
In the template, we can then make a membership check of the set:
{% for emp in emps %}
<td>
{% if emp.id not in empprocess %}
<button class="btn btn-info">Edit</button>
{% else %}
<button class="btn btn-info">Assign</button>
{% endif %}
</td>
{% endfor %}
Note: you might want to rename your field username to user since a ForeignKey to a user is not the same as a username.
Note: please use {% url ... %} template tags [Django-doc] instead of performing URL processing yourself.

Related

How can i retrieve context from for loop in views django and send it to template

I need to do one page with topic and all entries about this topic. And for each entries I need all comments shown up below each entry. Comments should be for exact entry. Cant find it solution and decided ask. Thank you.
models.py
--snip--
class Comment(models.Model):
date_added = models.DateTimeField(auto_now_add=True)
text = models.TextField()
owner = models.ForeignKey(User, on_delete=models.CASCADE)
entry = models.ForeignKey(Entry, on_delete=models.CASCADE)
def __str__(self):
return f"{self.text[:50]}..."
views.py
--snip--
def topic(request, topic_id):
topic = Topic.objects.get(id=topic_id)
entries = topic.entry_set.all()
comments = []
for entry in entries:
c = entry.comment_set.all()
comments.append(c)
context = {'topic': topic, 'entries': entries,
'comments': comments}
return render(request, 'learning_logs/topic.html'
,context)
topic.html
{% extends 'learning_logs/base.html' %}
{% block content %}
<p>{{ topic.title }}</p>
<p>{{ topic.description }}</p><br>
<p>Entries:</p><br>
<ul>
{% for entry in entries %}
<li>{{ entry.text }}</li>
<ul>
<p>Comments:</p>
{% for comment in comments %}
<li>{{ comment.text }}</li>
{% endfor %}<br>
</ul>
{% empty %}
<li>Not entries</li>
{% endfor %}
</ul>
{% endblock content %}
You can do this with just topic. No need to get entries and comments:
{% extends 'learning_logs/base.html' %}
{% block content %}
<p>{{ topic.title }}</p>
<p>{{ topic.description }}</p><br>
<p>Entries:</p><br>
<ul>
{% for entry in topic.entry_set.all %}
<li>{{ entry.text }}</li>
<ul>
<p>Comments:</p>
{% for comment in entry.comment_set.all %}
<li>{{ comment.text }}</li>
{% endfor %}<br>
</ul>
{% empty %}
<li>Not entries</li>
{% endfor %}
</ul>
{% endblock content %}
You will also want to optimise the query using prefetch_related so you don't hit the db per entry per comment:
topic = Topic.objects.prefetch_related('entry_set__comment_set').get(id=topic_id))
context = {'topic': topic}
return render(request, 'learning_logs/topic.html', context)

Wagtail Uploaded Document direct URL

I am trying to generate a url to an uploaded document (PDF, DOC...etc) on my search results page. Search is returning the items but there seems to be no url field. There is a file field which seems to have the file name, but I am unable to get a link back to this file. I am using the stock document model. Is there some sort of special tag that needs to be used like with the images?? At my wits end.
Search view
if search_query:
results = []
page_results = Page.objects.live().search(search_query)
if page_results:
results.append({'page': page_results})
doc_results = Document.objects.all().search(search_query)
if doc_results:
results.append({'docs': doc_results})
img_results = Image.objects.all().search(search_query)
if img_results:
results.append({'image': img_results})
search_results = list(chain(page_results, doc_results, img_results))
query = Query.get(search_query)
# Record hit
query.add_hit()
and the template page.
{% for result in search_results %}
{% for k, v in result.items %}
{% if k == 'page' %}
{% for item in v %}
<p>
<h4>{{ item }}</h4>
Type: Article<br>
Author: {{ item.specific.owner.get_full_name }}<br>
Publish Date: {{ item.specific.last_published_at}}
</p>
{% endfor %}
{% elif k == 'docs' %}
{% for item in v %}
<p>
<h4>{{ item.title }}</h4>
Type: Document<br>
Publish Date: {{ item.created_at }}
</p>
{% endfor %}
{% elif k == 'image' %}
{% for item in v %}
<p>
{% image item original as item_img %}
<h4>{{ item.title }}</h4>
Type: Image<br>
Publish Date: {{ item.created_at }}
</p>
{% endfor %}
{% endif%}
{% endfor %}
{% endfor %}

Angular, Django undefined value from Django

I have a get_context_data in my view
def get_context_data(self, **kwargs):
context = super(MyView,self).get_context_data(**kwargs)
humans = Human.objects.all()
context['humans'] = [{'fname': i.first_name, 'lname':i.last_name} for i in humans]
return context
When I have this:
{% for human in humans %}
<tr>
<td>{{human.fname}} {{human.lname}}</td>
</tr>
{% endfor %}
It works fine. I get
John Doe
Michael Smith
etc...
but, when I've tried put this values to angulary by:
{%verbatim%}
...
<button ng-controller="MyCtrl" type="submit" ng-click="
{%endverbatim%}
myFunc({{human.fname}},{{human.lname}})
{%verbatim%}">
Send
</button>
...
{%endverbatim%}
I've got only undefined:
#in my controller:
#...
$scope.myFunc = function(fname, lname){
$log.log(fname, lname); // <- this returns 2x undefined
}
Guys, any ideas?
The Django verbatim looks like this:
{% verbatim %}
{{if dying}}Still alive.{{/if}}
{% endverbatim %}
https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#verbatim
You have the {% endverbatim %} tag before {% verbatim %} in your snippet.
<button ng-controller="MyCtrl" type="submit" ng-click="
{%endverbatim%}
myFunc({{human.fname}},{{human.lname}})
{%verbatim%}">
Send
</button>
I've solved it
myFunc("{{human.fname}}","{{human.lname}}")
instead
myFunc({{human.fname}},{{human.lname}})

How can I access specific array in twig for symfony?

I have a problem, I only want to access a specific location of array,
Lets say I have this code
{% set total = val.listCompanies|length%}
{% if total > 1 %}
<td>
<button id="viewcompany"
type="button"
class="pop btn btn-info"
data-toggle="popover"
title="User Company List"
data-content='
{% for key1, val1 in val.listCompanies %}
{{ val1.CompanyName }}<br>
{% endfor %}'
data-placement="right"
data-html = "true">
see company
</button>
</td>
{% endif %}
{% if total < 2 %}
<td>
{% for key1, val1 in val.listCompanies %}
<center>
{{ val1.CompanyName }}<br>
</center>
{% endfor %}
</td>
{% endif %}
I want to make a button, that if it contain only one array inside it, I dont have to use the popover button, but if it has more than 1 array inside of its, then I have to show it inside of the popover button.
The thing is I cant access the specific array, to add more logic..
If your val.listCompanies contains numeric keys, you can access the first one by using:
val.listCompanies[0]
If your val.listCompanies has generated keys and you want to access the first one, you can use:
val.listCompanies|first
If your val.listCompanies has generated keys and you want to access the Nth one, you can use:
val.listCompanies|slice(n, 1)|first
Working demo

google app angine template: loop and check the existence of the corresponding entity

I need to create a 100-cell table, and in each cell if the corresponding entity exists, display it's information, otherwise, display "Empty". How do I do that? The python program (Item has properties of "seqNumber" and "name"):
query = db.Query(Item)
items = query.fetch(100)
render(..., {'range100':range(100), 'items':items}, ...)
HTML:
<table>
<tr>
{% for i in range100 %} <!-- for item in items (how?) -->
<td>
{% if item.seqNumber == forloop.counter (how?) %}
{{item.name}}
{% else %}
Empty
{% endif %}
{% endfor %}
</tr>
</table>
query = db.Query(Item)
items = query.fetch(100)
l = []
for i in enumerate(range(99)):
try:
l.append((i,items[i].name))
except:
l.append((i,None))
render(stuff = l)
This is all untested and the try/except is no doubt not ideal, just easier to write code then in a comment to give you the general idea of how I'd approach this.
<table>
<tr>
{% for i in stuff %}
<td>
{{ i.0 }}<!-- ID -->
{% if i.1 %}
{{ i.1 }}<!-- value -->
{% else %}<!-- if the value is none -->
"VALUE NEEDED"
{% endif %}
{% endfor %}
</tr>
</table>

Resources