Passing currently logged user to submit_line.html in Django - django

I have been trying to get the currently logged user object in submit_line.html to control which buttons it displays. However I have realized that the user object is not passed to the context for submit_row. What would be the best way to pass a the currently logged user object to submit_row. Should I create a new template tag?
Nicola

You can get the current User by accessing the request object:
{{ request.user }}
Just make sure 'django.core.context_processors.request' is included in context_processors setting in settings.py:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
...
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
...
'django.core.context_processors.request', # this entry is important
],
},
},]

Yes you can also use {{ request.user }} in your template to get login user. And also you can use template tag to get login user for that
first create .py file let's consider 'templatetags.py' and write this view there
#register.assignment_tag(takes_context=True)
def user_tag(context):
request = context['request']
return request.user
Now load this templatetags.py file in your html file i.e.'submit_line.html'
{% load templatetags %}
{% user_tag as user %}
{% if user %}
{{ user }}
{% endif %}
Hope this will help you.

Related

Django extend tab into tabular.html existing file

How do I extend/edit the "admin/edit_inline/tabular.html"?
I have this into my settings.py:
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [os.path.join(BASE_DIR, "Metamanager/templates")],
.....
}
My admin.TabularInLineinside the admin.py:
class FileInline(admin.TabularInline):
model = UploadFile
template = os.path.join(BASE_DIR, "Metamanager/templates/tabular.html")
and into my custom template:
{% load i18n admin_urls static admin_modify %}
{% block table_content %}
<td class="original"><p>holaaaaaaaaaaaaa</p></td>
{%endblock%}
not showing the td into the body as I don't know what need to extend into the custom html exactly from tabular.html.
I want to make the link redirect to a view I have don for direct downloading
I need to extend the tabular.html auto created by Django bear in mind I don't have Forms at all, the screenshoot is a Django FileField rendered from models.py

How to display Model in each HTML template?

But create a request in each functions inside views.py I do not want.
Is it possible to output the model in each template using only one request?
I tried to use templateetags but
that so
#register.simple_tag(takes_context=True)
def header_categories(context):
return Categorie.objects.all().order_by('id')
what is like that
#register.simple_tag(takes_context=True)
def header_categories(context):
categories = Categorie.objects.all().order_by('id')
args = {}
for cat in categories:
args[cat.text] = {
'id':cat.id,
}
if cat.parent:
args[cat.text]['parent_id'] = cat.parent.id
args[cat.text]['parent_text'] = cat.parent.text
return args
Nothing works correctly
{% for cat in header_categories %}
cat.text
{% endfor %}
I tried through js
var arr = {%header_categories%}
but django changes everything
{'dresses': {'id': 19},
Before going deeper into your question, I think you should have
{% for cat in header_categories %}
{{ cat.text }}
{% endfor %}
You need to make a custom context processor (See Using RequestContext [Django docs]). What this would do is add a variable to the context for each template. Quoting the documentation:
The context_processors option is a list of callables – called
context processors – that take a request object as their argument and return a dictionary of items to be merged into the context.
In some suitable app of yours make a file named context_processors.py and add this code in it:
def header_categories(request):
return {'header_categories': Categorie.objects.all().order_by('id')}
Now in your settings in the TEMPLATES settings add this context processor to the list context_processors, so it should look like:
[
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'your_app.context_processors.header_categories',
]
Now in your templates you can simply write:
{% for cat in header_categories %}
{{ cat.text }}
{% endfor %}

What is the best way to pass a parameter from views into an anchor tag?

I'm building a dashboard that has a button on a sidebar that allows a user to update their data. Which currently looks like this:
<a class="nav-link" href="{% url 'form-update' pk=id %}"> Questionnaire </a>
I'm trying to connect that id field to my views.py:
def dashboard(request):
user = request.user
account = 0
id = Form.objects.filter(author=user,account=account).values('id').get('id')
context = {
'id':id
}
return render(request, 'dashboard/index.html',context)
url pattern:
path('update/<int:pk>', FormUpdateView.as_view(),name='form-update')
I'm not sure the best way to send this data to the href tag?
EDIT
It seems to be an issue because this dashboard html file is a base HTML file that I use with other templates. If I load the data in a child template than it loads fine, just not at the parent html file.
views.py:
def dashboard(request):
user = request.user
account = 0
id = Form.objects.get(author=user,account=account)
context = {
'id':id.id
}
return render(request, 'dashboard/index.html',context)
urls.py:
<a class="nav-link" href="{% url 'form-update' pk=id %}"> Questionnaire </a>
If anyone stumbles across this, the issue actually arose from passing a variable to a base HTML file. In this case, you have to create a file in your app (context_processors.py) then create a function in there:
def add_variable_to_context(request):
user = request.user
account = 0
pk = Form.objects.filter(author=user,account=account).values('id').last().get('id')
return {
'id': pk
}
Then register this py file in settings.py context_processors.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'dashboard.context_processors.add_variable_to_context',
],
},
},
]
You can then call that variable in the normal fashion.
<a class="nav-link" href="{% url 'form-update' pk=id %}">Questionnaire</a>

showing dynamic data from database in all views

I'm using Django 2.0
I have a Model within my notes application
notes/models.py
class ColorLabels(models.Model):
title = models.CharField(max_lenght=50)
In the sidebar navigation which will be displayed on all pages, I want to show the list of color labels and it will show on all pages.
How can I show dynamic data in all views or say on all pages?
Use a custom template context processor.
This will add the context (data) you need into the templates rendered by all views.
First create the context processor (notes/context_processors.py):
from .models import ColorLabel
def color_labels(request):
return {'color_labels': ColorLabel.objects.all()}
Then add it to the context_processors option of your template renderer in settings.py:
TEMPLATES = [{
'BACKEND': '...',
'OPTIONS': {
'context_processors': [
'notes.context_processors.color_labels',
...
],
},
}]
Finally, you will be able to use it in your templates:
templates/base.html
<nav>
{% for color_label in color_labels %}
{{ color_label.title }}
{% endfor %}
</nav>

Sending context with request, and {% if %} not working properly

I have a problem trying to figure out why below will render an html page showing 'hi' and 1, instead of just 1.
views method.
def index(request):
context = {
'test' : 1,
}
return render(request, 'index.html', context)
template html. Rendering index.html will show both 'hi' and 1. But there's no user in context, so why is the if user going through?
{% if user %}
<h1>hi</h1>
{% endif %}
{% if test %}
<h1>{{ test }}</h1>
{% endif %}
The answer is Django's builtin context processor called django.contrib.auth.context_processors.auth. It is enabled by default which means an auth.User object representing the currently logged-in user is sent to all templates with the name user automatically.
From docs:
The context_processors option is a list of callables – called context processors – that take a request object as their argument and return a dictionary of items to be merged into the context.
In the default generated settings file, the default template engine contains the following context processors:
[
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
]
if there is a user logged in django will create a AUTH_USER_MODEL representing the currently logged-in user. Also from the request object you can access the user model without specifying context. For example if a user is logged in you can do request.user.username and the username will appear in the template.