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).
Related
We have a web app(Django based backend and Node/ReactJs based front-end, MySQL based DB), and a Flutter based mobile app. We are creating a system where a vendor can create a meeting invite and list the time (and timezone) at which the meeting starts.
Visitors for that meeting should be able to see the time (and timezone) in their local time.
We will be having visitors' location and timezone ID based on their IP.
I can't figure out how to display the list of timezones(preferably in the GMT+xxxx format ) in the front-end for the vendor to choose when he creates an invite and in what format it should be sent to the backend and stored so that I am able to convert it and display it to the visiting user based on his location's timezone?
I would be really grateful if someone here can point me to the right question if it has been asked already or some document from which I can refer to for the implementation?
You can use pytz for creating a list of timezones.
There's documentation in Django stating how to select current timezone and creating a list of timezones link
Create a list of timezone select option
# views.py
import pytz
def your_views(request):
# code
return render(request, 'your_template.html', {'timezones': pytz.common_timezones})
In your_template.html file
<select name="timezone">
{% for tz in timezones %}
<option value="{{ tz }}">{{ tz }}</option>
{% endfor %}
</select>
Normal people don't like GMT+X. Second, basing a timezone on IP is irritating for people using VPNs, especially since the browser stores a timezone based on computer settings. Granted, it takes a request to be sent via javascript, so the first page won't know what the timezone is. See Intl.DateTimeFormat.resolvedOptions().timeZone.
To generate choices that correspond with that list, use pytz.common_timezones:
import pytz
class YourModel(models.Model):
TZ_CHOICES = ((v, v) for v in pytz.common_timezones)
time_zone = models.CharField(choices=TZ_CHOICES)
My script is to hide some pages for the some login User. My script get trigger well in Client not in Webplayer.
To trigger this script i created the Data function property with Input and output parameter.
Input parameter as sysdate
output assigned to document property where below script is present.
import Spotfire.Dxp
from Spotfire.Dxp.Data import *
table=Document.Data.Tables["RestrictedSSO"]
minCol=table.Columns['GROUPNAME']
minCursor=DataValueCursor.Create(minCol)
for row in table.GetRows(minCursor):
Document.Properties["UserGroup"]= minCursor.CurrentValue;
if Document.Properties["UserGroup"]=="Restricted":
for Page in Document.Pages:
if Page.Title == "ABCD":
Document.Pages.Remove(Page)
if Page.Title == "EFGH":
Document.Pages.Remove(Page)
First check if there is a URL specified for the TERR Engine. A default setting might work in the client and not in the webplayer, so specifying the URL can ensure it works in both Client and Webplayer.
If that still does not help you can choose to initiate the python script via Javascript instead of the TERR sysdate output : https://community.tibco.com/wiki/how-trigger-python-script-report-load-javascript-tibco-spotfire
When using TERR Check whether you have have checked refresh automatically and unchecked allow cache from script in data function.
Run terr on server rather than run locally.
Go to file-> Document properties -> uncheck Remember personalized view for each web client user.
Even after doing the above steps if it didn't worked , then you can also go with java script.
I have an input text box which will be used for newsletter sign ups. I want to store these emails in a table in a SQL Server database.
I have the database set up, I just don't know how I would post the data to it.
By the way the site is set up using Umbraco if that makes any difference.
If you have no experience with Umbraco or c# programming a MailChimp umbraco package might maybe help:
http://our.umbraco.org/projects/mailchimp4umbraco
Although this is not a good approach, it can be done using a Razor file. I suggest you read this blog post to get a better understanding of how you SHOULD do it: http://creativewebspecialist.co.uk/2013/07/16/umbraco-petapoco-to-store-blog-comments/
Umbraco uses petapoco under the covers. PetaPoco is a light weight database query/update tool. So you can use this to access the database table. If you don't know petapoco, this is a good time to digg in. :-)
You can add c# code inside your razor script. Everything between #{ ... } can be plain old c# code.
Below, we start with checking if the pages has been posted back. If it is, we run some code and return. If not, the rest of the page will be rendered.
#{
if(IsPost) {
var myNewValue = Request.Form["field1"];
var db = ApplicationContext.DatabaseContext.Database;
db.Update("articles", "article_id", new { title="New title" }, 123);
<div>save success</div>
return;
}
}
<form method="POST">
<input name="field1">
<button type="submit">submit</button>
</form>
Although it works (and I have done it multiple times), I don't advise you do use the code above because:
This is a very quick and dirty solution.
It doesn't follow best practices.
And it will not work with multiple forms on the same page.
(Although the last objection could be circumvented by adding a hidden field to check which form you submit...)
I have a custom permission model for my project and I'm not using django's default permissions backend. I have a custom has_permission template tag to check if the user has the specified permission or not.
The problem is that there's lots of queries done for the same checks every time, I'm looking for a way to reduce my Permission queries. What I'm doing inside my templates is like :
{% if user|has_permission:'jpermission.can_edit_jpermission' or
user|has_permission:'jgroup.can_edit_jgroup' or
user|has_permission:'role.can_edit_role' %}
and the code for has_permission template tag is as follows :
rep = perm_name.split('.') # rep is for e.g. "jpermission.can_edit_jpermission"
ctn_type = rep[0]
codename = rep[1]
pr = JPermission.objects.filter(model_name=ctn_type, codename=codename)
if pr.exists():
if user.has_perm(pr[0]):
return True
Specifically talking, the problem is that every time i check even for the exactly same if statements, lots of queries are made (from what I'm doing, it's obvious there will be).
Is there any other way i can go at it ? like query all permissions once, cache them, and do something like how prefetch_related is handled to prohibit further db queries (python filtering with loops and ... ) ?
P.S: has_perm is also overridden and checks if users role, group or permissions have the specified permission or not)
There are multiple solutions for this.
Move permissions to user model as methods of model and use cached_property decorator so that consecutive calls to methods does not hit database again.
Store the permissions state in session when user logged in, and later use session data to check for permissions.
It looks like you are using django-guardian, and it is already caching the permissions:
Once checked for single object, permissions are stored and we don’t
hit database again if another check is called for this object. This is
great for templates, views or other request based checks (assuming we
don’t have hundreds of permissions on a single object as we fetch all
permissions for checked object).
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.