How I can get User.username and Group.name - django

I need to get the username and the name of group for all user.
The model that I use are User(default) and Group(default)
index.html:
{% for dato in usuarios %}
{{dato.first_name|title}}
{% for item in jefes %}
{{dato.groups}}
{% if dato.groups == item.id %} #I don't know to do this if
{{item.name}}
{% endif %}
{% endfor %}
{% endfor %}
view:
def inicio(request):
usuarios = User.Group.all()
grupos = Group.objects.all()
ctx = {'usuarios':usuarios,'grupos':grupos}
return render_to_response('index.html', ctx, context_instance=RequestContext(request))

You do not need the groups queryset from the view.
{% for dato in usuarios %}
{{dato.first_name|title}}
{% for group in dato.groups.all %}
{{group.name}}
{% endfor %}
{% endfor %}

Related

{% empty %} does not work in django template

if works correctly but empty does not work, here is my code:
{% for answer in ans|slice:":3" %}
{% for course in crs %}
{% if answer.course_id == course.id %}
<h4 class="w3-text-blue">{{answer.course}}</h4>
{% endif %}
{% empty %}
<h1>empty</h1>
{% endfor %}
{% endfor %}
and this is my views:
class CourseListView(ListView, LoginRequiredMixin):
model = Course
template_name = 'course_list.html'
def get_context_data(self, **kwargs):
context_data = super(CourseListView, self).get_context_data(**kwargs)
context_data['crs'] = Course.objects.raw('SELECT * FROM ertaapp_course where prof_id=%s',[self.request.user.id])
context_data['ans'] = Answer.objects.raw('SELECT * FROM ertaapp_answer')
return context_data
Why you want to do that, just use {% if %} and {% else %}:
views.py
def get_context_data(self, **kwargs):
context_data = super(CourseListView, self).get_context_data(**kwargs)
context_data['crs'] = Course.objects.raw('SELECT * FROM ertaapp_course where prof_id=%s',[self.request.user.id])
ans = Answer.objects.all()
context_data['ans'] = ans
context['ans_count']=ans.count()
return context_data
Now, in html template
{% if ans_count > 0 %}
{% for answer in ans|slice:":3" %}
{% for course in crs %}
{% if answer.course_id == course.id %}
<h4 class="w3-text-blue">{{answer.course}}</h4>
{% endif %}
{% endfor %}
{% endfor %}
{% else %}
<h1>empty</h1>
{% endif %}

Displaying Nested ManyToMany Relation

I'm having nested many to many relation in my models.py and I've got the display partially working. I have 2 questions:
Is there a way to simplify the presentation, e.g. by inlineformset?
How to I access nested context variables in the template form (see line {% for objective in selected_objectives %} )?
Please let me know if there is a way to make my question more clear
models.py
class Process(models.Model):
title = models.CharField(max_length=200)
desc = models.TextField('process description', blank=True)
def __str__(self):
return self.title
class Objective(models.Model):
process = models.ManyToManyField(Process, verbose_name="related processes", blank=False)
title = models.CharField(max_length=200)
desc = models.TextField('objective description', blank=True)
def __str__(self):
return self.title
class Risk(models.Model):
objective = models.ManyToManyField(Objective, verbose_name="related objectives", blank=False)
title = models.CharField(max_length=200)
desc = models.TextField('risk description', blank=True)
def __str__(self):
return self.title
views.py
#login_required
def detailed_list(request):
#context = RequestContext(request)
obj = []
ri = []
all_processes = Process.objects.order_by('id') #[:1]
for p_index,p in enumerate(all_processes):
obj.append(p.objective_set.all()) #appending objectives for each process
for o_index,o in enumerate(obj[p_index]):
ri.append(o.risk_set.all().values()) #appending risks for each objective
context = {'all_processes': all_processes,
'selected_objectives': obj,
'selected_risks': ri
}
return render(request, 'repository/detailed.html', context)
template detailed.html
<p>Create new Process
</p>
{% if all_processes %}
No: {{ all_processes|length }}
<ul>
{% for process in all_processes %}
<li>{{ process.title }} {{ forloop.counter0 }}</li>
<ul>
{% if selected_objectives %}
{% for objective in selected_objectives %}
<!-- see here --> <li>{{ objective.title }} {{ forloop.counter0 }} - {{ objective.desc }}</li>
{% endfor %}
{% else %}
<p>No objectives are available.</p>
{% endif %}
</ul>
{% endfor %}
</ul>
{% else %}
<p>No processes are available.</p>
{% endif %}
all you have to do is just pass the Process object as the context to your template
context = {'all_processes': all_processes}
and in you template :
<p>Create new Process
</p>
{% if all_processes %}
No: {{ all_processes|length }}
<ul>
{% for process in all_processes %}
<li>{{ process.title }} {{ forloop.counter0 }}</li>
<ul>
{% if all_processes.objective_set.all %}
{% for objective in all_processes.objective_set.all %}
<li>{{ objective.title }} {{ forloop.counter0 }} - {{ objective.desc }}
</li>
{% endfor %}
{% else %}
<p>No objectives are available.</p>
{% endif %}
</ul>
{% endfor %}
</ul>
{% else %}
<p>No processes are available.</p>
{% endif %}
<!-- this is if you want to show risks -->
{% for process in all_processes %}
{% for objective in all_processes.objective_set.all %}
{% for risk in objective.risk_set.all %}
{{ risk.desc }}
{% endfor %}
{% endfor %}
{% endfor %}
I hope this is what you were expecting !

Django: get profiles having auth.Group as foreign key

I have an model which uses auth.models.Group as foreign key called Dashboard:
class Dashboard(models.Model):
d_name = models.CharField(max_length=200)
d_description = models.CharField(max_length=200)
d_url = models.CharField(max_length=200)
d_status = models.CharField(max_length=200)
owner = models.ForeignKey(Group)
def __str__(self):return self.d_name
my views.py is:
def custom_login(request):
if request.user.is_authenticated():
return HttpResponseRedirect('dashboards')
return login(request, 'login.html', authentication_form=LoginForm)
def custom_logout(request):
return logout(request, next_page='/')
def user(request):
context = {'user': user, 'groups': request.user.groups.all()}
return render_to_response('registration/dashboards.html', context,
context_instance=RequestContext(request))
and here using this dashboards.html I want to display the dashboards by using the Group_name which i will get as a result of group.name:
{% extends "base.html" %}
{% block content %}
{% if user.is_authenticated %}
<p>Welcome, {{ request.user.get_username }}. <br/>
{% else %}
<p>Welcome, new user. Please log in.</p>
{% endif %}
<ul>
{% for group in groups %}
<li>
<strong>{{ group.name }}<strong> -
{{ dashboards.d_name }}{% if not forloop.last %},{% endif %}
</li>
{% endfor %}
</ul>
{% endblock %}
here I have mentioned all the supporting information for my problem, please let me know if there are any solution.
To access the list of Dashboards for the Group use the group.dashboard_set queryset:
{% for group in groups %}
<li>
<strong>{{ group.name }}</strong> -
{% for dashboard in group.dashboard_set.all %}
{{ dashboard.d_name }}{% if not forloop.last %},{% endif %}
{% endfor %}
</li>
{% endfor %}
This queryset is called "backward relationship".
views.py
def user(request):
user= request.user
groups = request.user.groups.all()
dashboards = Dashboard.objects.filter(owner=groups)
context = {
'user': user,
'groups': groups,
'dashboards': dashboards,
}
return render_to_response('registration/dashboards.html', context, context_instance=RequestContext(request))
and dashboards.html
{% extends "base.html" %}
{% block content %}
{% if user.is_authenticated %}
<p>Welcome, {{ request.user.get_username }}. <br/>
{% else %}
<p>Welcome, new user. Please log in.</p>
{% endif %}
<ul>
{% for group in groups %}
<li>
<strong>you belongs to::{{ group.name }}</strong> </li>
{% endfor %}
</ul>
<strong>#Dashboards available are::</strong>
{% for Dashboard in dashboards %}
<ol>
<li>{{ Dashboard.d_name }}-{{ Dashboard.owner }}-{{Dashboard.d_description}}</li> </ol>
{% endfor %}
{% endblock %}
this works good and neat,,,,

pagination shows same results on every page in django

I have the following view that gets and paginates search results:
def search(request):
query=request.GET.get('q','')
form=SearchForm({'q': query })
results = form.search()
paginator = Paginator(results, 15)
print 'page is: '+request.GET.get('page')
try:
page = paginator.page(int(request.GET.get('page')))
except InvalidPage:
raise Http404("No such page of results!")
for result in page.object_list:
print result.object.name
#this prints the same every time!
context = {
'view':resolve(request.path_info).url_name,
'form':form,
'page':page,
'query':query,
}
return render(request, 'nutrition/food-log.html', context)
My template looks like the following:
{% if query %}
<h3>Results</h3>
{% for result in page.object_list %}
<p>{{ result.object.name }}</p>
{% empty %}
<p>No results found.</p>
{% endfor %}
{% if page.has_previous or page.has_next %}
<div>
{% if page.has_previous %}{% endif %}« Previous{% if page.has_previous %}{% endif %}
|
{% if page.has_next %}{% endif %}Next »{% if page.has_next %}{% endif %}
</div>
{% endif %}
{% else %}
{# Show some example queries to run, maybe query syntax, something else? #}
{% endif %}
Does anyone know why this is happening?

How can I get a variable passed into an included template in django

I am a Django newbie and am unable to achieve something trivial. Please help me with this.
I am setting a variable pgurl in my views.py
Am able to access the variable {{pgurl}} in my with_tag.html template. This template includes a pagination.html template into itself
In pagination.html I am unable to use the variable {{pgurl}} and nothing is printed
How can I get this variable passed into the included template?
views.py
def with_tag(request, tag, template_name='main/with_tag.html', current_page=1, pgurl=''):
if request.method == 'GET':
query_tag = Tag.objects.get(name=tag)
primes = TaggedItem.objects.get_by_model(Prime, query_tag)
primes = primes.order_by('-date')
request.page = current_page
tcm_pp = TCM_ITEMS_PER_PAGE
pgurl = request.path
else:
return HttpResponseRedirect(request.path)
return direct_to_template(request, template_name, { 'primes' : primes, 'prime_total' : Prime.objects.count(), 'now': datetime.now(), 'page' : current_page, 'tcm_pp' : tcm_pp, 'tag' : tag, 'pgurl' : pgurl })
with_tag.html
{% extends "base.html" %}
{% load comments %}
{% load pagination_tags %}
...
{% include "pagination.html" %}
{% paginate %}
pagination.html
{% if is_paginated %}
{% load i18n %}
<div class="pagination">
{% if page_obj.has_previous %}
‹‹ {% trans "previous" %}
{% else %}
<span class="disabled prev">‹‹ {% trans "previous" %}</span>
{% endif %}
{% for page in pages %}
{% if page %}
{% ifequal page page_obj.number %}
<span class="current page">{{ page }}</span>
{% else %}
{{ page }}
{% endifequal %}
{% else %}
...
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
{% trans "next" %} ››
{% else %}
<span class="disabled next">{% trans "next" %} ››</span>
{% endif %}
</div>
{% endif %}
It will be helpful if you post the output of the rendered page. The context should get passed, might be your template tags instead. Try to do assert and check to see if the variables were passed correctly.