I would like to show the total number of employees registered in my database. Using the count function.
My views.py:
def home(request):
return render(request, 'dashboard.html')
def return_total_employees(request):
return_total = Employees.objects.aggregate(total=Count('EmployeeCard'))[
'total'
]
return render(request, 'dashboard.html', {'return_total ': return_total })
My template:
<h1> {{ view.return_total_employees }} </h1>
The dict you're returning in the render function is called context. You can access the value of returned context in your template like this
{{return_total}}
Related
How can i query User model to get user informations like: username, email, first name, and last name into his profile. I want to display all these information in his profile page.
as you can see here in the Profle view i'm willing to access user email, but how can i query the database to get all these information in the profile page ?
def profile(request, pk):
user_profile = User.objects.filter(email=request.user)
context = {'user_profile':user_profile}
return render(request, 'profile.html', context)
the profile template:
<p>{{user.email}}</p>
If you are looking for the logged_in user details, you already have that as part of the request object. So you can use the following in your template without doing a lookup in your view:
<p>Username: {{request.user.username}}</p>
<p>Email: {{request.user.email}}</p>
If you want to use the PK value being passed to your view, so that a visitor can visit the profile of another user (eg, the Primary Key is to identify another user account) you can do a lookup on that. As Sunderam Dubey notes, the best method for that is via a get_object_or_404() call in your view
views.py
from django.shortcuts import get_object_or_404
def profile(request, pk):
user = get_object_or_404(User,id=pk)
context = {'user_context':user}
return render(request, 'profile.html', context)
profile.html
<p>Email : {{user_context.email}}</p>
<p>Username : {{user_context.username}}</p>
Note the variable object names with _context at the end. You don't have to follow this naming convention, but what's important is that the things I have named 'user_context' have the same name.
If you want to access only current logged in user information so you should not use filter() as it gives you queryset and used via loops which we run in templates. You should use get_object_or_404[django-doc] for displaying data of single object. It gives 404 if found nothing.
Views.py
from django.shortcuts import get_object_or_404
def profile(request, pk):
single_user = get_object_or_404(User,pk=pk)
context = {'single_user':single_user}
return render(request, 'profile.html', context)
Template file
{% if single_user %}
<p>Email : {{single_user.email}}</p>
<p>Username: {{single_user.username}}</p>
<p>first name : {{single_user.first_name}}</p>
<p>last name: {{single_user.last_name}}</p>
{% else %}
<p>user is not coming</p>
{% endif %}
I solve my problem by doing this in the profile view:
def profile(request, pk):
user_context = get_object_or_404(User,id=pk)
context = {'user_context':user_context}
return render(request, 'profile.html', context)
I can now be able to access all user information in the template by:
<div class="container">
<div class="row justify-content-center">
<p>Email: {{user.email}}</p>
<br>
<p>Username {{ user.username }}</p>
</div>
</div>
I'm trying to plot graphs based on the values of the form variables in my django template.
I have 4 variables (ChoiceFields) in my form
I want my second choice field to change the choices with respect to the value of first variable
Eg. is var1='age' var2_options=['M','F']
if it is var1='Education', var2_options=['Bachelors','Masters','High School']
here's my code:
views.py-
class HomeView(TemplateView):
template_name='charts.html'
def get(self, request):
form = HomeForm()
return render(request, self.template_name, {'form':form})
def post(self,request):
form=HomeForm(request.POST)
if form.is_valid():
text_1 = form.cleaned_data['post_1']
global z
z=text_1
text = form.cleaned_data['post']
global b
b=text
text1 = form.cleaned_data['post1']
global c
c=text1
text2 = form.cleaned_data['post2']
global d
d=text2
args = {'form':form, 'text_1':text_1,'text':text, 'text1':text1, 'text2':text2}
return render(request, self.template_name, args)
charts.html (template)
<form method="POST">
{%csrf_token%}
{{form.as_ul}}
<button type="submit">get</button>
{{form.as_ul}}
<button type="submit">PLOT GRAPH</button>
</form>
forms.py
class HomeForm(forms.Form):
post_1 = forms.ChoiceField(choices=((None,None),('लिंग :','sex :'),('शिक्षण:','education:'),('जात :','caste :'),('व्यवसाय :','occupation :')))
post = forms.ChoiceField(choices=((None,None),('लिंग :','लिंग :'),('शिक्षण:','शिक्षण:'),('जात :','जात :'),('व्यवसाय :','व्यवसाय :')))
post1 = forms.ChoiceField(choices=((None,None),('लिंग :','लिंग :'),('शिक्षण:','शिक्षण:'),('जात :','जात :'),('व्यवसाय :','व्यवसाय :')))
post2 = forms.ChoiceField(choices=((None,None),('bar','bar'),('horizontalBar','horizontalBar'),('line','line')))
I have arrays of choices ready for each variable
How can I pass one variable and then assign the choice field of next variable according to it?
Follow vitors explanations here
How to Implement Dependent/Chained Dropdown List with Django
In Django, when rendering data in templates that's available through the request, we have 2 options:
Obtain the data in the view, and pass it to the template engine through the context:
def my_view(request):
username = None
if request.user.is_authenticated:
username = request.user.username
context = {'username': username}
return render(request=request, template_name='test.html', context=context)
With a template that has:
<p>Hello, {{ username }}<p>
Directly obtain the value from the request in the template:
def my_view(request):
if request.user.is_authenticated:
return render(request=request, template_name='test.html', context={})
With a template that has:
<p>hello, {{ request.user.username }}</p>
Is there a difference between both in terms of 'correctness'?
Is request in the second template just to be seen as a context for the request object or are there other implications?
They are correct, generally speaking you are most likely to encounter the following pattern
def my_view(request):
user = request.user
context = {'user': user}
return render(request=request, template_name='test.html', context=context)
and
<p>hello, {{ user.username }}</p>
Usually you don't pass the request, but the user directly. Then since there could be many relevant user methods the user.<something> notation is used in the template.
Depending on your use case, though, if the only field you will need from the user is the username on that page, there's nothing wrong with passing it directly.
I have two forms as shown below
class TicketView(ObjectEditView):
form_class = forms.FirstForm
form_class2 = forms.SecondForm
model = First
def get(self, request, pk):
first = get_object_or_404(First, pk = pk)
return render(request, 'my_folder/file.html', {
'first': first,
'form': self.form_class,
"form2":self.form_class2
})
For the second form there is a drop down,with status as open, close and hold.
I am getting the drop down well using the below code
{% render_field form2.status %}
but it's not displaying current value as selected.
Is there anyway to assign current value of the drop down to the template and then set that value as selected in the drop down using the render_field?
Something like
{% render_field form2.status value='close' %}
I have this sample of django code:
# views.py
def test_view(request):
form = TestForm(
request.POST or { 'text': 'some text'},
)
data = {
'form': form,
}
print 'before rendering'
return render(request, 'test.html', data)
# forms.py
class TestForm(forms.Form):
text = forms.CharField()
def __init__(self, *args, **kwargs):
print 'init'
super(TestForm, self).__init__(*args, **kwargs)
def clean(self):
print 'in clean'
and this template:
#test.html
<form id='test-form' method="post" action="some url" enctype="multipart/form-data">
{{ form.as_p }}
<input type="submit" value="Save"/>
</form>
when i send get request to this file i have this output in console:
before renderinginit in clean
when I write {{ form.text }} instead of {{ form.as_p }} I have only:
before renderinginit
It seams to me that as_p method calls clean() internally in process of rendering template.
Before that I mentioned that as_p method only is some kind of shortcut(I understand that it's a method of Form class) and doesn't realize logic.
Why does it happen? Is it a bug or some usefull feature?
Version of Django==1.5.1
As far as I can see in the source django has a _html_output helper function to return the function form.as_p(). If there is data bound to the form (like yours), then the BaseForm class property errors is called. This function calls the forms full clean. So I think this behaviour is intentionally to render form errors.
Change your view like this:
# views.py
def test_view(request):
if request.POST:
form = TestForm(request.POST)
# this is usually used when there's an actual post request
# and in this block you do validation
else:
form = TestForm(initial={'somekey': 'somevalue'})
data = {
'form': form,
}
print 'before rendering'
return render(request, 'test.html', data)
and clean() won't be called anymore
The problem is that I unproper initialize form, I should use Form(initial={#something#})