Django Changing Date Input Format - django

I have a simple booking form which is having a date input in a line like:
reservation.html
<textarea name="booking" class="form-control" id="reservation"
value="{{placement.date|date:'d/m/Y'}}"></textarea>
models.py
class Lib(models.Model):
booking = models.DateField(null=True, blank=True)
My database postgresql based and also store date as in "date" format. I would love to change date-input like dd/mm/yyyy
I also tried to use placement.date|date type format in double quotes like:
<textarea name="booking" class="form-control" id="reservation"
value="{{placement.date|date:"d/m/Y"}}"></textarea>
But its still accept as mm/dd/YY. Is there any problem about my placement? My forms.py kinda simple like:
from django.forms import ModelForm
from .models import Lib
from django.utils import formats
class LibForm(ModelForm):
class Meta:
model = Lib
fields = ['title','name','email','booking']
I searched on google and on stackoverflow and found something on Django - Setting date as date input value and django how to format date to DD/MM/YYYY but i couldn't find anything that could help me. I have to seek help here as a last resort. Thanks in advance.

Related

Django-filter package, filtering by date (using calendar)

I am learning Django and have difficulties with django-filter package.
I am creating a NewsPortal as my homework. It shows news and i have to make a filter which could list the news by date. Plus i need to use a calendar to choose a proper date for filtering. Not just to write a date in a form but choose it by using the calendar.
The problem is that i am using a django-filter package and it creates its own form. Like this:
<form action="" method="get" class="filter_news">
{{ filterset.form.as_table }}
<input type="submit" value="Search" /></form>
I`ve created a FilterSet:
class PostFilter(FilterSet):
...
time_add = django_filters.DateTimeFilter(lookup_expr='gte', label='Date')
class Meta:
model = Post
fields = ['title', 'post_author_id__author_id__username', 'time_add']
My model:
class Post(models.Model):
...
time_add = models.DateTimeField(auto_now_add=True)
...
Right now filtering is not working at all and i don`t know how to make it by embedding calendar.
Please help me if you can. I am completely stuck.

Change date format in Django admin page [duplicate]

I recently added a new model to my site, and I'm using an admin.py file to specify exactly how I want it to appear in the admin site. It works great, but I can't figure out how to get one of my date fields to include seconds in it's display format. I'm only seeing values like "Aug. 27, 2011, 12:12 p.m." when what I want to be seeing is "Aug. 27, 2011, 12:12*:37* p.m."
Try this in the ModelAdmin:
def time_seconds(self, obj):
return obj.timefield.strftime("%d %b %Y %H:%M:%S")
time_seconds.admin_order_field = 'timefield'
time_seconds.short_description = 'Precise Time'
list_display = ('id', 'time_seconds', )
Replacing "timefield" with the appropriate field in your model, of course, and adding any other needed fields in "list_display".
digging around I ended here but applied a different approach to my app.
Changing django admin default formats could be done changing the django locale formats for every type you want.
Put the following on your admin.py file (or settings.py) to change datetime default format at your django admin.
from django.conf.locale.es import formats as es_formats
es_formats.DATETIME_FORMAT = "d M Y H:i:s"
It will change the ModelAdmin's datetime formats on that file (or whole site if in settings).
It does not breaks admin datetime filters and order features as #Alan Illing has point out in comments .
hope this help in future
Extra info:
You can change it for every available locale in django, which are a lot.
You can change the following formats using this approach
from django.conf.locale.es import formats as es_formats
es_formats.DATETIME_FORMAT
es_formats.NUMBER_GROUPING
es_formats.DATETIME_INPUT_FORMATS
es_formats.SHORT_DATETIME_FORMAT
es_formats.DATE_FORMAT
es_formats.SHORT_DATE_FORMAT
es_formats.DATE_INPUT_FORMATS
es_formats.THOUSAND_SEPARATOR
es_formats.DECIMAL_SEPARATOR
es_formats.TIME_FORMAT
es_formats.FIRST_DAY_OF_WEEK
es_formats.YEAR_MONTH_FORMAT
es_formats.MONTH_DAY_FORMAT
If you've tried gabriel's answer but it did not work, try to set USE_L10N = False in settings.py, it works for me.
Note that if USE_L10N is set to True, then the locale-dictated format has higher precedence and will be applied instead
See: https://docs.djangoproject.com/en/2.0/ref/settings/#std:setting-DATETIME_FORMAT
The accepted answer is correct, however I found it a bit confusing to understand how/why it works. Below is a small example that I hope illustrates how to do this more clearly.
Django provides a few ways to display "custom" fields in your admin view. The way I prefer to achieve this behavior is to define a custom field in the ModelAdmin class and display that instead of your intended field:
from django.contrib import admin
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=50)
birthday = models.DateField()
class PersonAdmin(admin.ModelAdmin):
#admin.display(description='Birthday')
def admin_birthday(self, obj):
return obj.birthday.strftime('%Y-%m-%d')
list_display = ('name', 'admin_birthday')
Notice that instead of displaying the actual birthday field from the Person model, we define a custom field (admin_birthday) as a method in the PersonAdmin and display that instead by adding it to the list_display attribute. Furthermore, the admin.display() decorator modifies how Django will display this custom field in the admin view. Using this approach, the admin panel will show the NAME and BIRTHDAY fields but using your preferred date formatting for the date.
The reason I prefer this approach is you keep the Model field definitions separate from how you display them in the admin panel. You can read more about alternative approaches in the Django admin documentation.

Django change the way date field is displayed in django admin

That's it i want to change the way its displayed cause it says "noon" or "midnight" and i want i to display the exact hour
I've got this code on the field
date = models.DateTimeField(auto_now_add=True, default=datetime.date.today())
You have 3 options.
Override DATETIME_FORMAT, read here: datetime format
Use a form for your model and in the date attribute have some like this(
in input format, put whatrever you want):
date = forms.DateTimeField(input_format="%b %d %Y %I:%M%p")
Or just change the way you render your datetime field in the template:
{{ your_model.date_field|date:'Y-m-d H:i' }}

Django date filter not working in template

I'm having problems with formatting a date object in a django template. In models.py the object looks like this:
release_date = models.DateField(blank=True,null=True)
In the database it looks like this:
[release_date] date,
The call in the template which does not work is this:
<td>{{ row.release_date|date:"Y-m-d" }}</td>
If I remove |date:"Y-m-d" the output looks like this:
08/04/2014
With |date:"Y-m-d" there is no date at all, but the rest of the site looks fine and there also is no error message in the console.
I already tried to convert the datetime object in views.py to a string but somehow the object still appears as a datetime object in the template. Here is what I did in views.py:
data=Release.objects.all().order_by('-release_date')
#convert dates to format YYYY-MM-DD since conversion does not work in the template
for data_item in data:
if data_item.orig_plan_date is not None:
data_item.orig_plan_date = data_item.orig_plan_date.strftime('%Y-%m-%d')
Does anybody know how I can fix this problem?
Based on this post it looks like you can change the format your dates are saved into your DB so that you don't have to specify the way they are displayed.
In your situation I'd assume that if you edit your settings.py to include:
DATE_INPUT_FORMATS = ('%Y-%m-%d')
and hooked it up to the form/modelform you use to save the date to the db. maybe something like:
class YourDateModelformName(ModelForm):
yourDateField = DateField(input_formats=settings.DATE_INPUT_FORMATS)
class Meta:
model = YourDateModel

Save dutch date

I have an input field with the following value: 12-04-2012
This is a Dutch date that I want to save in the database. Database Field is Date.
How can I save a non English date into the database?
I tried:
HTML
<input id="id_delivery_date" type="text" value="12-04-2012" name="delivery_date">
DJANGO
def save(self, user, session):
self.order.delivery_date = self.cleaned_data['delivery_date']
self.order.save()
You could use datetime.strptime to parse the string and create a datetime object that can directly be assigned to the database field.
from datetime import datetime
datetime.strptime('12-04-2012', '%d-%m-%Y')
Another option would be to use string processing, but this is quite a hack and not recommended.
>>> '-'.join(reversed('12-04-2012'.split('-')))
'2012-04-12'
By Dutch date, I assume you mean the format is MM-DD-YYYY. You can parse this into a datetime object with
from datetime import datetime
datetime.strptime("12-04-2012", "%d-%m-%Y")