Django: get profiles having auth.Group as foreign key - django

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

Related

In which variable is the model instance stored in customized view?

How can I actually pick up values from my model in a customised template?
Let's assume for this example, the model for Request has an attribute "title".
Following views.py:
class RequestModelView(ModelView):
datamodel = SQLAInterface(Request)
extra_args = {'my_extra_arg':Request}
show_template = 'show_request.html'
list_columns = ['title','description','request_status']
and here the show_requests.html
{% extends "appbuilder/general/model/show.html" %}
{% block show_form %}
This Text is before the show widget
{{ super() }}
This Text is shown below..
<hr>
{{ (self.title) }}; {{pk}}; {{pk['title']}}
{% endblock %}
In which variable can I find my object?
The only parameter that works is {{pk}} (it shows the ID of the Request).
I was thinking of something like item['title']
Thanks.
A very similar question was asked on their Github. I think you would have to use something along these lines:
views.py
class RequestModelView(ModelView):
datamodel = SQLAInterface(Request)
list_columns = ['title','description','request_status']
add_template = 'show_request.html'
#expose('/show_request', methods=['GET', 'POST'])
#has_access
def show_request(self):
get_filter_args(self._filters)
self.extra_args = {'item': list_columns}
return super(RequestModelView, self).add()
show_requests.html:
{% extends "appbuilder/general/model/show.html" %}
{% block show_form %}
This Text is before the show widget
{{ super() }}
This Text is shown below..
<hr>
{{ item['title'] }}
{% endblock %}
Documentation is certainly not very clear in this aspect, but please check template-extra-arguments
I'm not sure if you would still need extra_args = {'my_extra_arg':Request}.
The following example should make things clear:
from .models import cars
beautiful_names = ["John", "Jane", "Bob"]
flowers = ["Aster", "Buttercup", "Roses"]
class IndexView(View):
template_name = "dashboard/dashboard_index.html"
def get(self, request, *args, **kwargs):
all_car_objects=cars.objects.all()
return render(request,
self.template_name,
context={"my_addresslist": beautiful_names,
"my_rose_list": roses},
"all_cars":all_car_objects)
In your template you can then do something like:
<h1>Beautiful Names</h1>
{% for name in my_addresslist %}
<p>{{ name }}</p>
{% endfor %}
<h1>Roses</>
{% if my_rose_list %}
{% for rose in my_rose_list %}
<p>{{ rose }}</p>
{% endfor %}
{% endif %}
<h1>Cars</>
{% if all_cars %}
{% for car in all_cars %}
<div>
<p>{{ car.name }}</p>
<p>{{ car.make }}</p>
<p>{{ car.model }}</p>
</div
{% endfor %}
{% endif %}
So for your example, it comes down to this:
class MyView(ModelView):
datamodel = SQLAInterface(MyTable)
extra_args = {'my_request_list':Request}
show_template = 'show_request.html'
<h1>Requests</>
{% if my_request_list %}
{% for request in my_request_list %}
<p>{{ request }}</p>
{% endfor %}
{% endif %}

is_paginated not working properly for class based views in Django

book_list.html
{% extends "base.html" %}
{% block content %}
<h3> Available books </h3>
{% if book_list %}
<ul>
{% for book in book_list %}
<li> {{book.title }} <small> by {{book.author }}</small></li>
<p>{{ book.summary }}
{% endfor %}
<ul>
{% endif %}
{% if is_paginated %}
<div class="pagination">
<span class="page-links">
{% if page_obj.has_previous %}
previous
{% endif %}
<span class="page-current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
</span>
{% if page_obj.has_next %}
next
{% endif %}
</span>
</div>
{% else %}
<h4> pagination not working</h4>
{% endif %}
{% endblock %}
class in views.py :
class BookListView(generic.ListView):
model = Book
paginate_by = 2
queryset =Book.objects.all()
urls.py :
urlpatterns =[
url('^$',views.index, name ='index'), # matching with an empty string
url('^books/$',views.BookListView.as_view(),name ='books'), #the one to which I am adding the paginator
url('^book/(?P<pk>\d+)/$',views.BookDetailView.as_view(),name='book-detail'),
]
Book model :
class Book(models.Model):
title=models.CharField(max_length=100)
author = models.ForeignKey('Author',on_delete=models.SET_NULL,null = True)
summary = models.TextField(max_length=200,help_text="Enter the description")
isbn = models.CharField('ISBN',max_length=13 ,help_text='13 Character ISBN number' )
genre = models.ManyToManyField(Genre,help_text = 'selct a genre for this book')
class Meta:
ordering =["title"]
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('book-detail',args=[str(self.id)] )
The book_list gets rendered perfectly, the problem is with the paginator, the is_paginated condition is not working and it executes the else statement, I have been trying for more than 3 hours, but couldn't find a solution, What Am I missing here ?
Django version : 1.11.2
Python : 3.5
Edit :
update 1: The problem was the paginate_by value was two, and the total items to display was also two hence it didn't initiate the is_paginated tag,It worked fine when I added one item more than paginate_by value.
use this, you had some problem with the if condition
{% extends "base.html" %}
{% block content %}
<h3> Available books </h3>
{% if object_list %}
<ul>
{% for book in object_list %}
<li> {{book.title }} <small> by {{book.author }}</small></li>
<p>{{ book.summary }}
{% endfor %}
<ul>
{% if is_paginated %}
<div class="pagination">
<span class="page-links">
{% if page_obj.has_previous %}
previous
{% endif %}
<span class="page-current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
</span>
{% if page_obj.has_next %}
next
{% endif %}
</span>
</div>
{% else %}
<h4> pagination not working</h4>
{% endif %}
{% else %}
<h4> No book</h4>
{% endif %}
{% endblock %}

RoutablePageMixin and breadcrumbs

A standard Wagtail breadcrumb system like this works perfectly if all of your pages are in a tree (parents/children):
{% block main %}
{% if self.get_ancestors|length > 1 %}
<ul class="breadcrumb">
{% for page in self.get_ancestors %}
{% if page.is_root == False and page.url != '/' %}
<li>{{ page.title }}</li>
{% endif %}
{% endfor %}
<li class="active">{{ self.title }}</li>
</ul>
{% endif %}
{% endblock main %}
But it falls down if some of your sub-pages are not actual children, but instead use RoutablePageMixin. Because the routable pages are really different instances of the parent, the breadcrumb trail stops short of making it down to the routable page.
I thought I could add some extra info to the context to detect the situation and special-case it, but all of the WT URL methods return the URL of the "parent" page (i.e. the actual instance), and besides there is no programmatic "title" that could be used in the breadcrumb.
What's the best way to have a breadcrumb system that works equally well for child pages and routable pages?
Answering my own question (Thanks Robert for the hint). In the route definition in the model, add something like:
ctx['routed_title'] = 'Staff'
Then modify the breadcrumb example above like this (check for existence of the new element on context and append to breadcrumbs):
{% block main %}
{% if self.get_ancestors|length > 1 %}
<ul class="breadcrumb">
{% for page in self.get_ancestors %}
{% if page.is_root == False and page.url != '/' %}
<li>{{ page.title }}</li>
{% endif %}
{% endfor %}
{# If this is a routable, add non-parent/child link from context #}
{% if routed_title %}
<li>{{ page.title }}</li>
<li class="active">{{ routed_title }}</li>
{% else %}
<li class="active">{{ self.title }}</li>
{% endif %}
</ul>
{% endif %}
{% endblock main %}
Maybe this can be of any help.
#route(_(r'^detail/(?P<activity_slug>[-\w]+)/$'))
def show_activity(self, request, activity_slug):
activity_model_class = self.activity_model_class
if not activity_model_class:
raise Http404('No activity model.')
else:
queryset = self.get_activity(activity_slug)
try:
activity = queryset.get()
except activity_model_class.DoesNotExist:
raise Http404('activity not found')
else:
self.current_url = self.get_url(
'show_activity',
kwargs = {'activity_slug': activity_slug}
)
Now the routable page has a current_url
def get_context(self, request, *args, **kwargs):
context = super().get_context(request)
context['current_url']= self.current_url
return context
And now it’s in the context.

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 !

How I can get User.username and Group.name

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 %}