How do I activate datepicker widget on custom form field? - python

For example, when I add custom ModelView:
class TaskModelView(ModelView):
pass
flaskadmin = Admin(name='Flasky', template_mode='bootstrap3', index_view=MyAdminIndexView(),
base_template='admin/mymaster.html')
flaskadmin.add_views(TaskModelView(models.Task, db.session))
I also get useful datepicker widget on appropriate DateTime fields:
But what about custom views and forms? I tried to add view same way, but inherited it from BaseView, then I created new form with DateTimeField from flask-admin and tried to render it:
from flask.ext.admin.form import DateTimeField, DatePickerWidget, DateTimePickerWidget
class AssebledChartForm(Form):
date_from = DateTimeField('From', format='%d.%m.%Y', widget=DateTimePickerWidget())
date_to = DateTimeField('To')
class AnalyticsView(BaseView):
<...>
return self.render('admin/analytic.html', form=form)
flaskadmin.add_view(AnalyticsView(name='Analytics', endpoint='analytics'))
but widget did not appear both on from and to fields:
How do I use flask-admin datepicker on my own forms?

You have to import DateTimePickerWidget like this:
from flask_admin.form import DateTimePickerWidget
and use it, for example, like this:
start = DateTimeField('Start', widget=DateTimePickerWidget())

As far as I remember, you can use either jQuery datepicker for this, or WTForms one, and not a flask.ext.admin.form.
Admin form is intended to be hidden from the end user, and exposing its API to the public user is strongly prohibited.
There was a similar question here
And you can see a good example on how to use WTForms DatePicker.

Your admin/analytic.html is not loading the javascript that handles the client side selection of dates. add the following to your template;
{% block tail_js %}
<script src="/static/vendor/jquery.min.js" type="text/javascript">/script>
{# use /static/bootstrap2/js/bootstrap.min.js if you are using bootstrap2 #}
<script src="/static/bootstrap3/js/bootstrap.min.js" type="text/javascript"></script>
<script src="/static/vendor/moment.min.js" type="text/javascript"></script>
<script src="/static/vendor/select2/select2.min.js" type="text/javascript"></script>
{% endblock %}
This should give you everything you need to make all the widgets work (Select2, DatePicker, etc).

Related

I want to use the if statement based on the existence of a web page

So basically i have a complicated scenario. I am current using Django to build a website and i have current made two apps. Both apps have almost identical fields. The field I would want to focus on though is the Information field(which they both have and which i have auto generated with the help of the Wikipedia model)
So the case here is that I want to create an if and else statement in the html in such a way that if the page i am hyperlinking to exists it would go to the link dealing with DetailView but if it doesnt exist I would redirected to the Create View
I should also note that the two apps have their names linked with the help of the foreign key but when i try to open information links using the same name , they gave me different pks
I dont feel like i explained my problem well enough but I hope someone can understand what i mean
UPDATE
ok I create the get function using
def get(self, request, *args, **kwargs):
try:
self.object = self.get_object()
except Http404:
return redirect('/create/')
context = self.get_context_data(object=self.object)
return self.render_to_response(context)
but i dont know how to use the CreateView fuction i created instead of the link i put
This is the Detail View Html
{%extends "home.html"%}
{%block head_title%} {{block.super}}{%endblock head_title%}
{% block content%}
<!-- verify authentication -->
{% if request.user.is_authenticated%}
<h3>{{object.title}}</h3><br/>
{% endif %}
<ul type="disc">
<div class="container">
<li><b>Artist: </b>{{object.Summary}}</li>
<li><b>Genre: </b>{{object.Genre}}</li>
<li><b>Bio: </b><br>{{object.Bio}}</li>
EDIT
</div>
</ul>
{%endif%}
{% endblock %}
This is my model
from django.db import models
from django.conf import settings
from Blog.models import MainPage
from django.urls.base import reverse
from Blog.Retrieve import retriever
from django.db.models.signals import pre_save,post_save
import InfoPedia
class InfoPedia(models.Model):
user =models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
Name =models.ForeignKey(MainPage,on_delete=models.CASCADE)
Location =models.CharField(max_length= 50,null=True,blank=True)
Information =models.TextField(null=True,blank=True)
TrackListing=models.TextField(null=True,blank=True)
Published=models.BooleanField(default=True)
Timestamp=models.DateTimeField(auto_now=True)
Updated=models.DateTimeField(auto_now=True)
def get_absolute_url(self):
# return f"/Blog/{self.slug}"
return reverse('InfoPedia:DetailView', kwargs={"pk":self.pk})
class Meta:
ordering=["-Updated","-Timestamp"] #orranges in order of updated
def get_tracklist(self):
return self.TrackListing.split(",")
def Information_create_pre_save( instance, sender, **kwargs):
instance.Information=retriever(instance.Name)
def rl_post_save_reciever(sender, instance,created,*args,**kwargs):
print("saved")
print(instance.Timestamp)
pre_save.connect(Information_create_pre_save, sender=InfoPedia)
post_save.connect(rl_post_save_reciever, sender=InfoPedia)
An alternative - rather than checking the if/else in the HTML, just make all the links to the DetailView URL.
Then, in the get() handler for the DetailView, you perform a queryset lookup for the object. If no object is found, then instead of displaying the DetailView HTML, return to the user a 302 redirect (i.e. a temporary redirect) to the CreateView for that object. So all your if/else logic is in the view function or class, instead of HTML.

Rendering Bokeh widgets in django Templates

I'm new to django and bokeh.
I was trying to render a simple bokeh plot supported by a few select options that essentially allow me to tweak my plot's content in a django web application.
The plots are rendered when the script and div elements obtained from the bokeh.embed.components() are passed to the template as context variables.
The same didn't work when i had a widget and a plot held in a bokeh.io.vform object.
I get the output right when i perform a bokeh.io.show(), by specifying the bokeh.plotting.output_file(), but I'm trying to get this running in my web application.
Am I missing anything? Or is there any other approach that serves my intent?
my code to just render a bokeh widget is as follows:
views.py
#django imports
from bokeh.embed import components
from bokeh.plotting import figure
from bokeh.io import vform
from bokeh.models.widgets import Select
def test(request):
s = Select(title="test", value="a", options=['a','b','c'])
script,div = components(s)
return render(request,'test.html',RequestContext(request,{'script':script,'div':div}))
test.html
<html>
<head>
<link href="http://cdn.bokeh.org/bokeh/release/bokeh-0.11.1.min.css" rel="stylesheet" type="text/css">
<script src="http://cdn.bokeh.org/bokeh/release/bokeh-0.11.1.min.js"></script>
</head>
{% load staticfiles %}
<body>
{{ div | safe }}
{{ script | safe }}
</body>
</html>
I would expect a select form element to be rendered when test.html is launched from test() in django. but doesn't happen.
BokehJS was recently split up into separate pieces to provide more flexible options for usage depending on what parts of the library are actually being used. Because loading resources is normally automatically handled in many cases, it was unintentioinally neglected to mention this split prominently in the docs. However, it is important to know about for embedding. There is an issue to update the docs, but what you need to know is that if you are using widgets, you now also need to load additional scripts from CDN:
http://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.11.1.min.js
http://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.11.1.min.css

Render django application within TextField

I am creating an application to display articles. In my model, I have a TextField that will contain the content of the article.
Now I would like to be able to render another application within my article. Let say I have a poll application and I would like to display a poll in the middle of the article. How can I do that ?
I tried by putting a {% render_poll 42 %} within the post but, as expected, it just display that within the generated page.
Should I create some kind of tag (like let say [poll=42]) and parse it before displaying the rendered html page ? (I use the markdown library, maybe I could extend it.) How can I do that to stay in a nice "django friendly" way ? I want that, when in the admin panel, I can easily insert poll (or other apps) within an article.
You could compile the TextField string as a template. Ie.:
from django.db import models
from django.template import Template, Context
class YourModel(models.Model):
body = models.TextField()
def render_body(self, context=None):
template = Template(self.body)
context = context or {}
context['object'] = self
return template.render(Context(context))
Then in the actual template, you could use {{ your_model.render_body }} rather than {{ your_model.body }}.

how to extend django views/templates in a forward looking way

i'm looking for a way to extend a django template/view.
my first implementation consists of two models (clients/models.py):
class Client(models.Model):
...
class Address(models.Model):
client = models.ForeignKey(Client)
...
and its fairly simple template (clients/detail.html) :
{{client.name}}
Address: {{client.address.street}}, {{client.address.zipcode}} {{client.address.city}}
as my application grows, a new app was born: 'invoices'.
it is again very simple (invoices/models.py):
class Invoice(models.Model):
client = models.ForeignKey(clients.models.Client)
...
now my clients details-view needs to display invoices, so i create and override clients/detail.html in my 'invoices' app.
good for now.
later on i created a third app 'quotes'.
again my clients details-view needs to display quotes.
if i create clients/detail.html in my 'clients' i will loose the ability to display invoices.
because the 'invoices' and 'quotes' app are indipendent.
my first idea was to create something like a SubView-class
which 'invoices' and 'quotes' can extend and then register their implementation somewhere.
a template should look like this:
{{client.name}}
Address: {{client.address.street}}, {{client.address.zipcode}} {{client.address.city}}
{% for view in views %}
<h1>{{view.title}}</h1>
{{view.get_html}}
{% endfor %}
is this a good way to go and should i use a admin.site-like implementation for registering my sub-views?
In Django one url in urls.py should ideally use one view, just to keep things simple.
I would therefore adopt the approach of putting all the required context in your one view for this screen (I think you already have this via foreign keys in your model). Then, rather than doing what you call "SubView-class" I would go for the Django template include tag.
Example:
{% for invoice in client.invoices %}
{% include "invoice-detail.html" with invoice=invoice %}
{% endfor %}
This renders each invoice's detail for all the invoices of the client. Notice how this is in line with the DRY principle.

How do I add data to an existing model in Django?

Currently, I am writing up a bit of a product-based CMS as my first project.
Here is my question. How can I add additional data (products) to my Product model?
I have added '/admin/products/add' to my urls.py, but I don't really know where to go from there. How would i build both my view and my template? Please keep in mind that I don't really know all that much Python, and i am very new to Django
How can I do this all without using this existing django admin interface.
You will want to wire your URL to the Django create_object generic view, and pass it either "model" (the model you want to create) or "form_class" (a customized ModelForm class). There are a number of other arguments you can also pass to override default behaviors.
Sample URLconf for the simplest case:
from django.conf.urls.defaults import *
from django.views.generic.create_update import create_object
from my_products_app.models import Product
urlpatterns = patterns('',
url(r'^admin/products/add/$', create_object, {'model': Product}))
Your template will get the context variable "form", which you just need to wrap in a <form> tag and add a submit button. The simplest working template (by default should go in "my_products_app/product_form.html"):
<form action="." method="POST">
{{ form }}
<input type="submit" name="submit" value="add">
</form>
Note that your Product model must have a get_absolute_url method, or else you must pass in the post_save_redirect parameter to the view. Otherwise it won't know where to redirect to after save.
This topic is covered in Django tutorials.
Follow the Django tutorial for setting up the "admin" part of an application. This will allow you to modify your database.
Django Admin Setup
Alternatively, you can just connect directly to the database using the standard tools for whatever database type you are using.

Categories

Resources