Flask Admin Custom View - python-2.7

I am pretty new to Flask/Flask-Admin.
I have followed the tutorial on flask admin and managed to get the admin panel working but slightly lost on how to get the below things implemented.
https://github.com/flask-admin/flask-admin/tree/master/examples/auth
When logged in as a normal user I can only see "home" page.
How can I expose other views to "normal user" and restrict actions such as read only etc.
I have created a "baseview" which is not associated with any other models as below:
class SitesView(MyBaseView):
#expose('/')
def index(self):
return self.render('views/testviews.html')
admin.add_view(SitesView(name='Test views', endpoint='test views'))
and html as below:
{% extends 'admin/master.html' %}
{% block body %}
{{ super() }}
{% if current_user.has_role('view1') %}
Site1
{% endif %}
{% if current_user.has_role('view2') %}
<a>Site2</a>
{% endif %}
{% if current_user.has_role('view3') %}
<a>Site3</a>
{% endif %}
{% if current_user.has_role('view4') %}
<a>Site4</a>
{% endif %}
{% endblock %}
This gives me a new tab with different views with works as expected.
What I am trying to achieve here is when user click the Site1 link they go to Site1 page within flask-admin interface but I am not sure how to do that. I could create a new route for this but the problem is I can't(don't know how to) extend flask admin template.
For example this works but it redirect the page outside flask-admin template:
#app.route('/views/')
def views():
return render_template('views/views1.html')
and modified the templates>admin>index.html page with below:
<ul class="lead text-center list-group">
{% if current_user.has_role('view1') %}
<li class="list-group-item">View1</li>
{% endif %}
{% if current_user.has_role('view2') %}
<li class="list-group-item">View2</li>
{% endif %}
{% if current_user.has_role('view3') %}
<li class="list-group-item">View3</li>
{% endif %}
{% if current_user.has_role('view4') %}
<li class="list-group-item">View4</li>
{% endif %}
</ul
I want to build the whole web site using flask admin so that I can keep user experience consistence. Am I doing this the wrong way?
Thanks for your time.
Please do let me know if you want me to provide more information on this issue.
Kind Regards.

So after going through documentations and tutorials I have found the solution to my issue.
For my first question:
When logged in as a normal user I can only see "home" page. How can I
expose other views to "normal user" and restrict actions such as read
only etc.
We can do this by overwriting our view functions is_accessible method as below:
def is_accessible(self):
if not current_user.is_active or not current_user.is_authenticated:
return False
if current_user.has_role('superuser') or current_user.has_role('user') or current_user.has_role('view1'):
return True
return False
For my second question we just need to give the endpoint as for our BaseView as below:
class MyView(BaseView):
#expose('/')
def index(self):
return self.render('views.html')
admin.add_view(MyView(name='Custom Views', endpoint='customviews'))
And then in your jinja template you need to call it:
href="{{ url_for('customviews.index') }}
Just one thing to note, doing this:
current_user.has_role('superuser') or current_user.has_role('user') or current_user.has_role('view1')
could get quite messy if we have so many roles, not sure how we would approach this but hoping this will help someone.
Thanks all.

I know this is an old question, but for the following code
current_user.has_role('superuser') or current_user.has_role('user') or current_user.has_role('view1')
What I like to do is having a hybrid_property (available on both Peewee and SQLAlchemy) inside my User class that consolidates these properties. So it'd look something like this:
#hybrid_property
def user_has_administrative_rights(self):
return self.has_role('superuser') or self.has_role('user')

Related

django how to display a tag only if the value coming from the database is not null?

The logic for showing a tag
{% if profile.facebook is not None %}<i class="facebook icon"></i>{% endif %}
i want to show the facebook icon only when the user has provided the link. if not i dont want to display the icon.
You can define your conditional as well:
{% if profile.facebook %}
<i class="facebook icon"></i>
{% endif %}
if your code not work, you can share more info, like your views.py etc.

Overridding Django Admin's object-tools bar for one Model

I am looking for the solution. I think a lot of different examples have confused me a little. I want to override the object-tools template in the Django admin.
I have one button on my model's tools:
I need one other same type of button "Upload file". This should redirect me to the another view which I want to design myself in the same admin base template (with just one upload file control).
[A]
Move "django.contrib.admin" in your INSTALLED_APPS to end of INSTALLED_APPS.
You can make template file
<your_app>/templates/admin/<your_app>/<your_model>/change_list.html
source code:
{% extends "admin/change_list.html" %}
{% block object-tools-items %}
<li>
<a href="<your-action-url>" class="addlink">
Upload file
</a>
</li>
{{ block.super }}
{% endblock %}
[B]
Add change_list_template into your ModelAdmin.
class MyModelAdmin(admin.ModelAdmin):
change_list_template = '<path-to-my-template>.html'
And write template like [A] source code.
It has become lot easier to accomplish what you're looking for since this question has been asked the first time.
The Django documentation has a section on how to override admin templates. To add a button to the changelist object tools, follow these steps:
Copy Django's version of the change_list_object_tools.html template file into your project's or app's template folder: templates/admin/<app>/<model>/change_list_object_tools.html.
You can obtain the file form your virtual env's site-packages folder:
cp $VIRTUAL_ENV/lib/python3.8/site-packages/django/contrib/admin/templates/admin/change_list_tools.html templates/admin/$APP/$MODEL/
Note that you might need to adjust the path to site-packages for your Python version.
Now open the template file. It will look liek this:
{% load i18n admin_urls %}
{% block object-tools-items %}
{% if has_add_permission %}
<li>
{% url cl.opts|admin_urlname:'add' as add_url %}
<a href="{% add_preserved_filters add_url is_popup to_field %}" class="addlink">
{% blocktrans with cl.opts.verbose_name as name %}Add {{ name }}{% endblocktrans %}
</a>
</li>
{% endif %}
{% endblock %}
Add the link to your custom view:
…
{% if has_add_permission %}
<li><a class="addlink" href="{% url 'upload-file' %}">Upload file</a></li>
<li>
…
That's it! If you didn't know: you can add custom views and URLs to a ModelAdmin using ModelAdmin.get_urls() (docs). To not have to hardcode your custom admin URLs, you can of course reverse them (docs).
You can try to use https://github.com/texastribune/django-object-actions.
This will allow you to add buttons with custom logic. Though, I'm not sure whether you'll be able to a buttom for your list screen, as I did it only for a model-edit page.

How to check if current visitor is shop's admin?

I would like to create a product that will be available in Shopify's storefront but only accessible for the shop administrator. Is there a way to identify if the current user is an admin via liquid? Or is there any other solution for this. Thanks!
If you're signed in as an admin, when rendering the {{ content_for_header }} include, it will contain some JavaScript to push the page content down to make room for the Shopify admin bar.
We can utilize capture to store the {{ content_for_header }} code as a liquid variable and then use the contains operator to check if admin_bar_iframe exists in the variable.
{% capture CFH %}{{ content_for_header }}{% endcapture %}{{ CFH }}
{% if CFH contains 'admin_bar_iframe' %}
{% assign admin = true %}
{% endif %}
{% if admin %}
<!-- User is an admin -->
{% else %}
<!-- User is not an admin -->
{% endif %}
Note: I've noticed that the Shopify admin bar doesn't populate at all times (I think its a bug). If your Shopify admin bar is not populating on your instance this will not work.
Just figured out this method that works. (Basically the same thing as the old method, just another way around!)
Detecting logged in admin viewing site:
{% if content_for_header contains 'adminBarInjector' %}
<script>
console.log("You're a logged in admin viewing the site!");
</script>
{% endif %}
Detecting admin in design mode:
{% if content_for_header contains 'designMode' %}
<script>
console.log("You're an admin in design mode!");
</script>
{% endif %}
Another approach would be to use Customer Accounts. Liquid provides a {{ customer }} object, which is only present when a user (customer) is logged in.
You can add a specific tag to an admin user and use liquid to verify if a tag is present:
{% if customer.tags contains "admin" %}
And of course you need to identify your product as 'admin-only', for example using tags:
{% if customer.tags contains "admin" and product.tags contains "admin" %}
<!-- render product -->
{% else %}
<!-- do nothing -->
{% endif %}
EDIT: This seems not to be working anymore since an update to Shopify.
I know this is late, but here is what I've used and it has worked correctly in my testing. This is adapted from the previous answers, but allows use for Customise Theme options, etc.
{% capture CFH %}{{ content_for_header }}{% endcapture %}{{ CFH }}
{% assign isAdmin = true %}
{% if CFH contains '"__st"' %}
{% if CFH contains 'admin_bar_iframe' %}{% else %}
{% assign isAdmin = false %}
{% endif %}
{% endif %}
This is a more complete version of that provided by kyle.stearns above (I can't comment on it because new). One of the main instances where admin bar doesn't load is when previewing themes. Here is the amended code which I've used (updated June 2018 - as Shopify edited the way we preview themes):
{% capture CFH %}{{ content_for_header }}{% endcapture %}
{% if CFH contains 'admin_bar_iframe' %}
{% assign admin = true %}
{% elsif CFH contains 'preview_bar_injector-' %}
{% assign admin = true %}
{% endif %}
{% if admin %}
<!-- User is an admin -->
<script>
alert ("do some work");
</script>
{% else %}
<!-- User is not an admin -->
<script>
alert ("please buy some stuff");
</script>
{% endif %}
If you're using Plus then you also have access to the User via api.
I know this is an old question, but it still shows on top in google searches.
There's now a much better way.
Using liquid:
{% if request.design_mode %}
<!-- This will only render in the theme editor -->
{% endif %}
Using javascript:
if (Shopify.designMode) {
// This will only render in the theme editor
}
Source: shopify.dev
Currently there isn't. You could perhaps try inspecting cookies and stuff to see if there's some identifying information that would let you know if the user is an admin, but it would be fragile.
This would also require rendering the items, but hiding them via CSS. Then you'd show them using JS after you've run your checks.
As stated, this would probably be really fragile.

Factorizing a header menu in Django template

I'm building a website using django with a header on top of every page, which basically is a menu with a few links, constant throughout the pages.
However, depending on the page you're on I'd like to highlight the corresponding link on the menu by adding the class "active". To do so, I am currently doing as follow: each page has a full menu block that integrates within a general layout, which does NOT contain the menu. For exemple, page2 would look like this:
{% extends "layout.html" %}
{% block menu %}
<li>Home</li>
<li>page1</li>
<li class="active">page2</li>
<li>page3</li>
{% endblock %}
The problem is that, beside from that solution being not so pretty, every time I want to add a link to the header menu I have to modify each and every page I have. Since this is far from optimal, I was wondering if any of you would know about a better way of doing so.
Thanks in advance!
You can create a custom templatetag:
from django import template
from django.core.urlresolvers import reverse, NoReverseMatch, resolve
register = template.Library()
#register.simple_tag
def active(request, view_name):
url = resolve(request.path)
if url.view_name == view_name:
return 'active'
try:
uri = reverse(view_name)
except NoReverseMatch:
uri = view_name
if request.path.startswith(uri):
return 'active'
return ''
And use it in the template to recognize which page is loaded by URL
<li class="{% active request 'car_edit' %}">Edit</li>
If you have a "page" object at every view, you could compare a navigation item's slug to the object's slug
navigation.html
<ul>
{% for page in navigation %}
<li{% ifequal object.slug page.slug %} class="active"{% endifequal %}>
{{ page.title }}
</li>
{% endfor %}
</ul>
base.html
<html>
<head />
<body>
{% include "navigation.html" %}
{% block content %}
Welcome Earthling.
{% endblock %}
</body>
</html>
page.html
{% extends "base.html" %}
{% block content %}
{{ object }}
{% endblock %}
Where navigation is perhaps a context_processor variable holding all the pages, and object is the current PageDetailView object variable
Disclaimer
There are many solutions for your problem as noted by Paulo. Of course this solution assumes that every view holds a page object, a concept usually implemented by a CMS. If you have views that do not derive from the Page app you would have to inject page pretenders within the navigation (atleast holding a get_absolute_url and title attribute).
This might be a very nice learning experience, but you'll probably save loads time installing feinCMS or django-cms which both define an ApplicationContent principle also.
You may use the include tag and pass it a value which is the current page.
For example, this may be a separate file for declaring the menu template only:
menu.html
{% if active = "a" %}
<li>Home</li>
{% if active = "b" %}
<li>page1</li>
{% if active = "c" %}
<li class="active">page2</li>
{% if active = "d" %}
<li>page3</li>
And call this from within your template like this:
{% include 'path/to/menu.html' with active="b"%} # or a or c or d.
Hope it helps!

Simple vote button in Django

I'm an absolute beginner to django (and programming in general), I've tried the django Polls tutorial and all went well, however I am trying to get a minimal voting button to work. Basically I have set up a database with two columns, my models.py looks like this
from django.db import models
class Imgurl(models.Model):
urlvar = models.URLField(max_length=200)# a URL linking to an image
urlvote = models.IntegerField(default=0)# my intended vote count
def __unicode__(self):
return self.urlvar
I have made an input box where I can copy and paste an image url, this image then displays on a separate page(this works fine). What I want is to have a voting button next to each displayed image, where a user can click on the button (I am trying to use a submit button) and the number of votes will increase in the db(no redirecting to a new page, or anything fancy).
I think this is a trivial question and I am trying to learn the basics of POST and database handling in django (also, I have read the relevant chapters in the djangobook... maybe I'm just a little slow?)
my views looks like this
def urlvotes(request):
if request.method=='POST':
if 'voteup' in request.POST:
v=Imgurl(forloop.counter)
v.urlvote +=1
else:
pass
votetotal=v.urlvote # attempt to give the template some kind of context
return render_to_response('display.html', {'votetotal':votetotal}, context_instance=RequestContext(request))
and my template looks like this:
{% extends "base.html" %}
{% block head %}Image display{% endblock %}
{% block content1 %}
Home
{% if links %}
<ul>
{% for link in links %}
<li><img src="{{ link }}"></li>
<li><form action="{% url urlvotes %}" method="post">
{% csrf_token %}
<input type="submit" name="voteup" value='vote'/></p>
<p>{{votetotal}}</p>
</form></li>
{% endfor %}
</ul>
{% else %}
<p>No uploads.</p>
{% endif %}
{% endblock %}
when I run this, as is, I get a csrf verification failed error
Any help would be greatly appreciated
Try adding the #csrf_protect to your view
#csrf_protect
def urlvotes(request):
if request.method=='POST':
if 'voteup' in request.POST:
v=Imgurl(forloop.counter)
v.urlvote +=1
else:
pass
votetotal=v.urlvote # attempt to give the template some kind of context
return render_to_response('display.html', {'votetotal':votetotal}, context_instance=RequestContext(request))