How to add content to the index page using Flask-Admin - flask

I am using flask-admin, and I want to add a dashboard to the home page. I found I can add a new page using:
admin = Admin(name='Dashboard', base_template='admin/my_master.html', template_mode='bootstrap3')
then:
admin.init_app(app)
and finally I added my_master.html, and added content. However, it is all static, how can I add custom data to that view?

I found the answer in the documentation: http://flask-admin.readthedocs.org/en/latest/api/mod_base/
It can be overridden by passing your own view class to the Admin constructor:
class MyHomeView(AdminIndexView):
#expose('/')
def index(self):
arg1 = 'Hello'
return self.render('admin/myhome.html', arg1=arg1)
admin = Admin(index_view=MyHomeView())
Also, you can change the root url from /admin to / with the following:
admin = Admin(
app,
index_view=AdminIndexView(
name='Home',
template='admin/myhome.html',
url='/'
)
)
Default values for the index page are:
If a name is not provided, ‘Home’ will be used.
If an endpoint is not provided, will default to admin Default URL route is /admin.
Automatically associates with static folder. Default template is admin/index.html

According to flask-admin documentation use this:
from flask_admin import BaseView, expose
class AnalyticsView(BaseView):
#expose('/')
def index(self):
return self.render('analytics_index.html', args=args)
admin.add_view(AnalyticsView(name='Analytics', endpoint='analytics'))

Related

flask-admin AdminIndexView error could not build url for endpoint '/admin.static' with values ['filename', 'v']. Did you mean 'admin.static' instead?

I want to customize flask-admin AdminIndexView's index view
class CustomAdminIndexView(AdminIndexView):
#expose('/')
def index(self):
return super(CustomAdminIndexView, self).index()
admin = Admin(name=app_config["APP_NAME"], template_mode="bootstrap4", endpoint="/admin",index_view=CustomAdminIndexView())
Following this code
It throws
BuildError
werkzeug.routing.exceptions.BuildError: Could not build url for endpoint '/admin.static' with values ['filename', 'v']. Did you mean 'admin.static' instead?
I only want to customize the Index view of the admin panel.

How to assign default value using url parameter changelist_filters?

In Django 2.0.6,
I want to assign default model field value when adding the data in Django Admin page.
Here is my code.
models.py
class a_model(models.Model):
a_field = models.foreignKey(~~)
~~~~
URL (Create page in Admin)
http://127.0.0.1:8000/admin/~~~/a_model/add/?_changelist_filters=a_field__exact%3D586632
I want to get 586632 in above url and assign default value to a_field in that page.
I try to this way in models.py
class a_model(models.Model):
#staticmethod
def default_id(request):
return 586632
a_field = models.foreignKey(~~,default=default_id.__func__,~~)
then, I see the default value is 586632 like that I expected.
I want to know how to get the url parameter value to assign default value in model class.
Help me..
I'm working with django admin; Inside the object modeladmin, I've override the 'get_changeform_initial_data' function in this way:
def get_changeform_initial_data(self, request):
from django.http import QueryDict
if request.GET.__contains__('_changelist_filters'):
params = QueryDict(request.GET['_changelist_filters'])
if 'acto__exact' in params:
return {'acto' : params['acto__exact']
}
So i get the initial value of the field 'acto' if is specified as a changelist_filter in the url.

Url rerouting after making an entry Django admin add page

After making an entry in django admin, django routes directly to entries page. What I want is to go to main admin page. Do I need to overwrite the admin views file or is there a way to extend it and change the url routing?
You can override the response_add() method (or response_change() for editing existing entries) inside your ModelAdmin class as follow:
def response_add(self, request, obj, post_url_continue=None):
return redirect('/admin') # Or whatever URL you want

No reverse match error. How to debug?

I am trying to link the databrowse.admin widget of django that rests here :
http://127.0.0.1:8000/admin/openmaps/open_layers/
I tried to put this in a template and it returned a reverse match error. How to debug ?
A
The URL Tag you are attempting to use is specified in the Django Documentation here (for version 1.4):
https://docs.djangoproject.com/en/1.3/ref/templates/builtins/#url
It's purpose is to keep the URLs in your links DRY (Don't Repeat Yourself), so that you don't have to change your link URLs between your dev, staging, production or any other server environments you may have.
The url tag takes a view or a reference to a view via a url name as its main argument, and any arguments that the view takes as second arguments. From the documentation:
{% url path.to.some_view v1 v2 %}
Where path is a package name, to is a module name and some_view is a view function. v1 and v2 are args that the view takes. It would look like so in path/to.py:
from django.http import HttpResponse
def some_view(request, v1, v2):
return HttpResponse("A response")
Furthermore, when dealing with the admin, you'll need to use the namespace admin using the URL namespace strategy, like so:
{% url admin:view_name %}
What you need to do is find the path to the view you are looking for, and create the URL using that path. To get you started, you can create a link to you your admin site index like so:
My Admin Site
These will create links for the admin logout, password change form, and app list, respectively:
Admin Logout
Change Password
The Application List
For the views on specific models within the admin, django uses the meta data on the models to construct their url names. You can do the same with your models to link to their admin pages, however, you'll need to construct their names programmatically (unless you know them). So if you had a model named Foo, you could link to its changelist view, add view, and delete view in the admin respectively by constructing their view names and using the reverse method on them:
In your view:
from django.core.urlresolvers import reverse
#...some view code...
#Get an instance of the model
bar = Foo.objects.all()[0]
prefix = "%s_%s_" % (Foo._meta.app_label, Foo._meta.module_name)
changelist_name = "%schangelist" % prefix
add_name = "%sadd" % prefix
delete_name = "%sdelete" % prefix
changelist_url = reverse(changelist_name)
add_url = reverse(add_name)
delete_url = reverse(delete_name, args=(bar.pk,)) #You need the id of the model you want to delete as an argument.
#...some more view code...
In your template
The Foo ChangeList
Add a Foo
Delete {{ bar.name }}
You'll likely have to do some digging into the guts of django or any particular extension you're using to get the exact url name that you want. If you can provide more detail about the model you're trying to access in the admin, I can provide a more specific answer.

For a django model, how can I get the django admin URL to add another, or list objects, etc.?

As much as I love the django documentation, the section on bookmarklets in the admin is strangely vague.
My question is this: If I'm in a view and I have a django model (or, in some cases, an actual object), how can I get to the relevant admin pages for that model (or object)? If I have the object coconut_transportation.swallow.objects.all()[34], how can I jump right to the admin page to edit that particular swallow?
Likewise, how can I get the URL for the admin page to add another swallow?
http://docs.djangoproject.com/en/dev/ref/contrib/admin/#reversing-admin-urls
obj = coconut_transportation.swallow.objects.all()[34]
# list url
url = reverse("admin:coconut_transportation_swallow_changelist")
# change url
url = reverse("admin:coconut_transportation_swallow_change", args=[obj.id])
# add url
url = reverse("admin:coconut_transportation_swallow_add")
You can retrieve this from the actual object instance, this worked for me:
from django.core import urlresolvers
from django.contrib.contenttypes.models import ContentType
content_type = ContentType.objects.get_for_model(object.__class__)
object_admin_url = django.core.urlresolvers.reverse("admin:%s_%s_change" % (content_type.app_label, content_type.model), args=(object.pk,))
See this: http://djangosnippets.org/snippets/1916/
You can actually retrieve the info without making a query to ContentTypes
Just add this to your model class:
def get_admin_url(self):
return urlresolvers.reverse("admin:%s_%s_change" %
(self._meta.app_label, self._meta.model_name), args=(self.pk,))