I want to visualize a big, indexed table - big enough for count(*) to be too slow for my use case. Here's my views.py code:
import django_tables2
from projectname.models import Growth
def dashboard(request):
class StatisticsTable(django_tables2.Table):
class Meta:
model = Growth
table = StatisticsTable(Growth.objects.all())
django_tables2.RequestConfig(
request
).configure(table)
return render(request, "plain_table.html", {'table': table,
'title': 'Growth dashboard',
'search': None})
I was looking for examples on how to use django_tables2.paginators.LazyPaginator here and so far only found that I should pass it as a paginate= in django_tables2.RequestConfig, but I still get a regular paginator if I pass a reference to the class there. What's the proper use of this class in this context?
RequestConfig(paginate={"paginator_class": LazyPaginator}).configure(table)
Related
There's a table 'comment' with column time-stamp. I want the time difference from the date comment has been created to current date and time like created '5 Days ago' somewhat. I have no idea how to do that from eloquent.
My controller is:
public function show($id)
{
$vehicles=vehicles::findorfail($id);
$user=users::where('id',$vehicles->Users_id)->get()->first();
//adding view count
$viewad=ads::where('Vehicleid',$id)->get()->first();
$viewcount=$viewad->views;
$ad = ads::find($viewad->id);
$ad->views=$viewcount+1;
$ad->save();
$comments=comment::where('vehicles_id',$id)->get();
return view('Bike.show',compact('vehicles','user','viewcount','comments'));
}
How can i accomplish this task? Can anyone tell me how to do it?
If you want it available in the view the easiest way is to make an attribute accessor in the model.
First import Carbon at the start of the file use Carbon\Carbon;.
Then create the attribute accessor in your Comment model:
public function getTimeDifferenceAttribute()
{
return $this->time_stamp->diffForHumans(Carbon::now);
}
(I've used snake_case for the timestamp attribute name because the kebab-case version you used isn't valid in PHP variable names.)
Then it's available from a comment as $comment->time_difference.
EDIT:
This answer assumed that the model was treating time_stamp as a date. If this is not the case you should also add protected $dates = ['time_stamp']; to the model.
Use Carbon. See Carbon for the details.
$comments=comment::where('vehicles_id',$id)->get();
$today=Carbon::now();
and the view:
#foreach($comments as $comment)
{{$comment->name}} Created {{$today->diffForHumans($comment->time_stamp)}}
#endforeach
You have to import the namespace to use Carbon:
use Carbon\Carbon;
I'm using Plone 4.1.4 and I'm trying to get dynamic sources for a schema.Choice to work, I need to populate country list which in turn depends on the context object.
I'm using this example:
http://plone.org/products/dexterity/documentation/manual/developer-manual/advanced/vocabularies
For IContextSourceBinder, example, an empty dictionary instead of actual context object is returned:
from zope import interface
from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm
from zope.schema.interfaces import IContextSourceBinder
import zope.schema
from z3c.form import form
class CountryGenerator(object):
interface.implements(IContextSourceBinder)
def __call__(self, context):
#context is == {}
import pdb; pdb.set_trace()
return SimpleVocabulary([
SimpleTerm(value="not_selected", title=_("Country Not Selected"))
])
class IStep(interface.Interface):
region = schema.Choice(title=_("Select your country"),
required=True,
source=CountryGenerator,
default="not_selected")
class Step(form.Form):
fields = field.Fields(IStep)
label = _("Step")
description = _("Select your country")
When debugging point is hit inside CountryGenerator.__call__() method and I examine context object, the latter turn out to be just an empty dictionary.
When I try to use named utility example in the article mentioned above, and the similar thing happens, context there is also {}.
Could anyone point me to what I might be doing wrong?
UPDATE
ZCML for the form wrapper that calls the form is
<browser:page
name="view"
for="Products.oldproduct.MyFolderishClass"
class=".file.RegionClass"
permission="zope2.View"
/>
Where RegionClass inherits from Form wrapper, could it be permission or traversal issue?
Because your source is a class, you need to instantiate it:
class IStep(interface.Interface):
region = schema.Choice(title=_("Select your country"),
required=True,
source=CountryGenerator(),
default="not_selected")
In certain circumstances, such as with using sub forms or complex form widgets (widget within a widget for list selections, etc), you need to follow the __parent__ pointers to a proper outer context for getting back to the Plone context.
By default a java.util.Date field is represented in a CRUD form as a simple "DATE" input.
public class DatedModel extends Model {
public Date creationDate;
in the CRUD admin I see:
creationDate [TEXTINPUT]
yyyy-MM-dd format.
Is there any way to have a DateTime input instead, on selected fields only (not all of them modifying the application.conf date.format)?
Is there a way to affect which "widget" is used for a given field in the 'automated' CRUD admin?
Something like this in your application.conf:
module.crud=${play.path}/modules/crud
date.format=yyyy-MM-dd hh:mm:ss
Then in the model:
package models;
import java.util.*;
import play.data.binding.As;
import play.db.jpa.*;
import play.data.validation.*;
import play.templates.*;
import play.mvc.Scope.*;
import javax.persistence.*;
import play.Logger;
import play.templates.JavaExtensions;
#Entity
public class Product extends Model {
#As(lang={"*"}, value={"yyyy-MM-dd hh:mm:ss"})
public Date creationDate;
}
Your controller:
package controllers;
import play.*;
import play.mvc.*;
import java.util.*;
import models.*;
public class Products extends CRUD {
}
Documentation
Working demo: https://github.com/saxxi/play-framework-test
I finally found in the documentation my answer:
You can indeed customize each field; a more extensive example can be found on the lunatech blog using jquery datatables which also shows how to modify pagination.
#{crud.table fields:['name', 'company']}
#{crud.custom 'company'}
<a href="#{Companies.show(object.company.id)}">
${object.company.name}
</a>
#{/crud.custom}
#{/crud.table}
PS.
#AditSaxena hint was good and indeed a simple solution; but not what I wanted because it's not acceptable that the 'hint' is not correct! Clearly confusing for a user!
So for a datetime input (the specific question) we can combine the annotation (described in the doc)
#As(lang={"*"}, value={"yyyy-MM-dd hh:mm:ss"})
with a custom hint, eg.
#{crud.custom 'mydate'}
<span class="crudHelp">
Date format: etcetc.
</span>
...
#{/crud.custom}
I'll also point out that you can write your own validator
Other related useful questions:
Is it possible in playframework to override the default save action in the CRUD controller and redirect to list after
Play! framework CRUD module: adding default values and change date format?
Play framework CRUD file upload about custom file upload fields
A Grails controller received is called with the following request parameters:
defaultPrice[0].amount 22
defaultPrice[0].currency 1
defaultPrice[0].id
defaultPrice[1].amount 33
defaultPrice[1].currency 3
defaultPrice[1].id
I've defined the following command class:
class PriceCommand {
BigDecimal amount
Integer currency
Integer id
}
I attempt to bind the request parameters to a `List' in the action
def save = {List<PriceCommand> defaultPrice ->
}
But within the action, defaultPrice is null.
It requires an command with existing list of data, with specified name, that will be filled with data from request.
Try
import org.apache.commons.collections.ListUtils
import org.apache.commons.collections.Factory
class PriceListCommand {
List<PriceCommand> defaultPrice = ListUtils.lazyList([], {new PriceCommand()} as Factory)
}
and use this command inside controller. It should works
I'm not sure if this is what your looking but it may help...
1.) I think indexed params only work if you have a parent-child or one-to-many relationship. For example you might need to introduce a PriceCommandParent which contains a list of PriceCommand. I may be wrong on this and I welcome any corrections.
2.) I've found that indexed params aren't as magically as some of the other areas of Grails/Groovy so sometimes i'd rather deal with the mapping myself. Below is how i've handled it in the past....
def things = []
params.each{name, value->
if (name.matches('^(thing\\[\\d+\\])$')){ //<-- look for 'thing[x]'
things.add(new Thing(params[name]);
}
}
Let me know if any of this is of help
Hey!
Just started working with Pylons in conjunction with SQLAlchemy, and my model looks something like this:
from sqlalchemy import Column
from sqlalchemy.types import Integer, String
from helloworld.model.meta import Base
class Person(Base):
__tablename__ = "person"
id = Column(Integer, primary_key=True)
name = Column(String(100))
email = Column(String(100))
def __init__(self, name='', email=''):
self.name = name
self.email = email
def __repr__(self):
return "<Person('%s')" % self.name
To avoid sqlite reusing id's that might have been deleted, I want to add AUTOINCREMENT to the column "id". I've looked through the documentation for sqlalchemy and saw that the sqlite_autoincrement can be issued.
An example where this attribute is given can be found here.
sqlite_autoincrement seems though to be issued when creating the table itself, and I just wondered how it can be supplied when using a declarative style of the model such as mine.
Try including a __table_args__ attribute with the arguments you would pass to Table constructors in the traditional (non-declarative) data definition style, e.g.:
class Person(Base):
__tablename__ = "person"
__table_args__ = {'sqlite_autoincrement': True}
If you have to include several arguments, use this form instead (dict has to be last):
__table_args__ = (
Unique('foo'),
# ...
{'sqlite_autoincrement': True}
)
From the Table configuration section of the Declarative SQLAlchemy documentation:
Table arguments other than the name, metadata, and mapped Column arguments are specified using the __table_args__ class attribute. This attribute accommodates both positional as well as keyword arguments that are normally sent to the Table constructor.