django what variables available in a template .html file? - html

I'm trying to figure out what objects and variables are available within the template .html file
This is in the view file
from django.contrib.auth import get_user_model
Userx = get_user_model()
class ProfileDetailView(DetailView):
template_name ='profiles/user.html'
def get_object(self):
username = self.kwargs.get("username")
if username is None:
raise Http404
return get_object_or_404(Userx,username__iexact=username, is_active=True)
In the user.html file
{% block content %}
username={{ user.username }}
{% endblock content %}
my questions
1. why is the name of the object in the user.html file called user?
how would one find documentation on the object names and fields of the user object?
how would one see all available variables accessible in a particular .html template"
Thank you for your help

This is the name defined to refer to the user object (hard to expect something else)
Here you can find every fields of this User object
You can use {% debug %} to inspect the context and A LOT of other informations, and this link can help you to find a specific keyword to use in the templates.
Check this post too, especially for the following line (helpful to inspect the debug output) :
{% filter force_escape %} {% debug %} {% endfilter %}

Related

Intellij IDEA HTTP Client - How can i save variable from response body

In JetBrains Doc says, that you can save a variable of response body to global variables:
//Saving a variable
> {%
client.global.set("auth_token", response.body.json.token);
%}
But in my IDE there is an error "Unresolved variable json" on statement ".json.token":
enter image description here
Can enyone help me? Is there possability of saving valiables values from request body to global variables for using them in next requests of the same http file at all?
Try access token variable doing this instead:
{%
client.global.set("auth_token", response.body.token);
%}
(Without the .json)
It works for me!
And then, you can access that variable doing this:
{{auth_token}}

How safe is using if statements in html with django?

How safe is using if statements in html templates with django? Eg.
{% if post.visibility == 'PUBLIC' %}
show something....
{% endif %}
How easy is it to change that from public to private if we don't filter it accordingly in the backend for hackers or other people?
It is perfectly safe. It is not 'in html' at all.
That code is being evaluated on the backend using the Jinja2 template engine. A frontend user can't edit your if statement at all because by the time the message reaches them Jinja2 has already deleted it and replaced it with the computed version.
See: https://en.wiktionary.org/wiki/render#Verb
Django template processing happens on server side. A visitor of the page will only see the final result, but not the if statements. It is thus not possible for him to access different content by changing the if statement (unless there is some other way to attack the server itself or inject different values into the if statement that are generated from user input).

Is there a way to request a specific dataset from a rest api?

Sorry if this seems dumb to some of you, I am a total noob and literally have no idea what I'm trying to google, so I can't even try googling this before I ask.
I would like to pull specifically england covid19 data from this page: https://services1.arcgis.com/0MSEUqKaxRlEPj5g/arcgis/rest/services/Coronavirus_2019_nCoV_Cases/FeatureServer/1/query?where=1%3D1&outFields=*&outSR=4326&f=json
and then set it as a json attribute (if possible).
I'm trying to create a sensor in Home Assistant for England Covid19 data, using the rest platform.
I am taking this idea from someone else who has already successfully acheived this:
platform: rest
name: covid_19_folkhalsomyndigheten
resource: https://www.arcgis.com/sharing/rest/content/items/2dc63e26f509468f896ec69476b0dab3/data
value_template: "{% if value_json.embedCode == '' %} Otillgänglig {% else %} Tillgänglig {% endif %}"
json_attributes_path: $.widgets.widget_1.config
json_attributes: [embedCode]
scan_interval: 21600
But there are differences in the actual resource he is using and mine so maybe I cannot just copy his method.
If anyone has the spare time to guide me through this I would be very greatful. Thanks!
Here ya go, here's an answer using python3
import json
import requests # you'll have to install this with something like pip
r=requests.get('https://services1.arcgis.com/0MSEUqKaxRlEPj5g/arcgis/rest/services/Coronavirus_2019_nCoV_Cases/FeatureServer/1/query?where=1%3D1&outFields=*&outSR=4326&f=json')
print(r.text, ' this will be your json object')
# if you want to write the data to a file called data.txt (note you can choose any name like corona.txt)
with open('data.txt', 'w') as outfile:
json.dump(r.text, outfile)
The following code would fetch the data, and then write and create a file called data.txt

Ansible use a template with blockinfile

blockinfile appears to do basic subsitutions with {{ templates. The documentation doesn't mention any templating capabilities.
However, it doesn't appear to be possible to do a full template, say with a loop. This fails with template error while templating string: unexpected '%'
blockinfile:
dest: /etc/haproxy/haproxy.cfg
marker: "# {mark} ANSIBLE CONFIG certs"
block: |
{% if certs %}
bind *:443 ssl crt {% for cert in certs %}{{cert}} {{% endfor %}
{% endif %}
This seems like a basic usecase, where I might like to do some one-off edits for a configuration file, but still need the power of templates.
Note that using with_items doesn't really do what I want here, because I need exactly 1 line.
I think the problem is that you have an extra { in the template.
bind *:443 ssl crt {% for cert in certs %}{{cert}} {{% endfor %}
should be
bind *:443 ssl crt {% for cert in certs %}{{cert}} {% endfor %}

Django passes incorrect query results to template

I am writing a web app that displays user profiles.
The profile includes a display of the user's interest in other users, which can be uni- or bidirectional. I am using django's included User model to handle authentication and authorization.
The problem I have is that under some circumstances the rendered pages present data from queries executed earlier. Specifically, this happens when I am using the app as two different users on the same computer but on different browsers (Chrome and Safari on OS X; using the django development web server). Right after I load a page for user 1, if I reload a page for user 2 I see user 1's query results.
I have confirmed that my queries are correct by printing them to the console. I think the problem may be at the web server, because the pages load the right queries right after a server restart.
Any ideas?
** Edit: as Daniel points out, the problem is that the interest_view function has a dictionary as a default parameter.**
Relevant code snippets:
models.py
class Profile(UserenaBaseProfile):
user = models.OneToOneField(User, unique=True)
class Interest(models.Model):
user = models.ForeignKey(User, related_name=u'interests')
interest = models.ForeignKey(User)
views.py
from django.http import HttpResponseForbidden
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
def interest_view(request, username, extra_context={}):
user = get_object_or_404(User, username__iexact=username)
profile = user.get_profile()
if not profile.can_view_profile(request.user):
return HttpResponseForbidden("You can't view this page.")
interests = Interest.objects.filter(user=user)
if len(interests) > 0:
extra_context['active_interests'] = interests
return render_to_response('interest_detail.html',
extra_context,
context_instance=RequestContext(request)
)
interest_detail.html
{% if active_interests %}
{% for interest in active_interests %}
<li>
{{ interest.interest.first_name }} {{ interest.interest.last_name }}
</li>
{% endfor %}
{% endif %}
You haven't shown any code, so this is impossible to debug. But the issue is almost certainly that you are defining queries at module level, where they persist for the lifetime of the process (which is many requests).
Edit:
Well, I was almost right - it is an issue with things being defined at module level, although in your case it's the Python default argument gotcha. See the effbot for a great explanation, although the default SO question on this is one: Least astonishment in Python.