This is a reasonably straight forward port of functionality provided by the `django.utils.dateformat` module into a method extending JavaScript's Date object. Its intended use is to allow client-side dynamic content to share the same date & time string formatting as Django template markup. By using this in conjunction with a context processor (to pass a format string to all templates) you can switch formats for both server-generated & client-generated dates across a complete site with a single setting.
The function supports *almost* the entire format -- as listed by the Django documentation for the [now template tag](http://www.djangoproject.com/documentation/templates/#now) -- with the exception of "I" & "T".
As a 'dumb' illustration, the following template tag usage:
It is {% now "jS F Y H:i" %}
...could equate to the following:
It is <script type="text/javascript">var now = new Date(); document.write(now.strfdate('jS F Y H:i'));</script>
It's not extensively tested (I only wrote it over the weekend), but seems to be working okay. Feel free to leave any corrections or suggestions in the comments, and I'll try to keep this entry updated if I make any fixes or changes.
After reading the comment to my [snippet #49](http://www.djangosnippets.org/snippets/49/) it occurs to me that Python properties may not be obvious to everyone, and may be underutilized in Django models.
Here is a simple example demonstrating a property to format a Person's name.
This class simplies the Feed class of django. The differences are:
1. Don't need define title and description template file
2. default feed generator class is Atom1Feed
3. According feed_url, EasyFeed can auto get the domain field, and you can also specify the domain parameter.(feed_url should be a full domain path, so you can use [Get the full request path](http://www.djangosnippets.org/snippets/41/) to get the full path of the feed url.)
4. There is a helper function render_feed() to return a response value.
example
---------
Feed class:
class BookCommentsFeed(EasyFeed):
def __init__(self, feed_url, book_id):
super(BookCommentsFeed, self).__init__(feed_url)
self.book_id = book_id
self.book = Book.objects.get(id=int(book_id))
def link(self):
return '/book/%s' % self.book_id
def items(self):
return self.book.comment_set.all().order_by('-createtime')[:15]
def title(self):
return 'Comments of: ' + self.book.title
def description(self):
return self.book.description
def item_link(self, item):
return '/book/%s/%s' % (self.book_id, item.chapter.num)
def item_description(self, item):
return item.content
def item_title(self, item):
return '#%d Comment for: ' % item.id + item.chapter.title
def item_pubdate(self, item):
return item.createtime
def item_author_name(self, item):
return item.username
And the view code is:
from feeds import *
from utils.easyfeed import render_feed
from utils.common import get_full_path
def bookcomments(request, book_id):
return render_feed(BookCommentsFeed(get_full_path(request), book_id))
Using newforms you can create forms from existing models easily and automatically with either `form_for_model(class)` or `form_for_instance(instance)`. Usually the automagically generated form fields are sufficient; however, sometimes you need to restrict selections in a choice field.
You can also set the default selection when instantiating the form. In this example, if `acct` is not contained in the 'account' field choices, the selection defaults to the first entry.
This example is probably not good practice when using `form_for_instance` because the existing value 'selection' of the choice field is lost and must be reset manually (see above).
Returns a sharpened copy of an image.
Resizing down or thumbnailing your images with PIL.Image tends to make them blurry. I apply this snippet to such images in order to regain some sharpness.
`foo = dynamic_import ( 'rawr.i.am.a.lion' )`
Will import `lion` from `rawr.i.am.a` and return it. (This isn't really Django specific)
Props to Crast for the original.
By popular demand an example of search in models that spans more realtions.
Keep a list of Q, filter the None away, feed the rest to .filter()
Credit goes to Carlo C8E Miron for the idea... cheers buddy! ;)
A more simple version of [https://djangosnippets.org/snippets/1688/](https://djangosnippets.org/snippets/1688/), inheriting from `SelectDateWidget`, overriding only the necessarily.
**Usage example:**
**In models.py:**
from django.db import models
from django.utils.translation import gettext_lazy as _
class MyModel(models.Model):
start = models.DateField(
_("Start date"),
)
end = models.DateField(
_("End date"),
)
class Meta:
verbose_name = _("My model")
**In forms.py:**
from django import forms
from .models import MyModel
from .widgets import MonthYearWidget
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
exclude = []
widgets = {
"start": MonthYearWidget(),
"end": MonthYearWidget(last_day=True),
}
**kwargs:**
- *last_day :* if set to `True`, returns the last day of the month in the generated date.
Provide the ability to disable a select option with Django2. This can be done during the widget initialization (i.e when the widget field is created) or during form initialization.
This will disable the select option based on a context or by specifying the values that should be disabled.
Decorator to automagically add placeholders to form widgets. `cls` can be any class derived from `django.forms.Form` or `django.forms.ModelForm`. The field labels are used as value for the placeholder. This will affect all form instances of this class.
* add_placeholders only to forms.TextInput and form.Textarea
* add_placeholders_to_any_field adds placeholders to any field
Usage:
@add_placeholders
class Form(forms.Form):
name = forms.CharField
The name field will render as `<input type="text" placeholder="name">`
This is useful when you don't want to put any `{% verbatim %}` tag in the file(s) you're including within template(s) (because you want it/them completely raw) and when you want to load such file(s) from static dir(s), as native `{% include %}` tag can't achieve that (still).
Put the provided code in *templatetags/rawinclude.py* in your Django app, and then use it in your template(s) like this:
`{% load rawinclude %}{% raw_include 'file.html' %}`
You're looking at the top-rated snippets currently on the site; if you'd like to contribute, sign up for an account and you'll be able to rate any snippet you see.