I want to have two record dates of a blog post, one is the date the post was created on, and the last time/date the post was updated. But the issues is the date_created variable reset every time I make any changes.
...
from datetime import datetime
class Post(models.Model):
...
date_created = datetime.now() # how to not reset this variable everytime when I update changes to the post?
last_edited_date = datetime.now()
You should use Django models fields. I suggest reading documentation as #Shivendra mentioned, but for a fast solution use these:
create_time = models.DateTimeField(auto_now_add=True)
update_time = models.DateTimeField(auto_now=True)
You should use DateField for this implementation. Please check this documentation for more info.
DateField.auto_now
Automatically set the field to now every time the object is saved.
Useful for “last-modified” timestamps. Note that the current date is
always used; it’s not just a default value that you can override.
DateField.auto_now_add
Automatically set the field to now when the object is first created.
Useful for creation of timestamps. Note that the current date is
always used; it’s not just a default value that you can override.
I have a model name CustomerProject and I want to track individually few fields when it was last updated. Right now I am using auto_now= True in datetime fields which can tell me when the whole model was last edited but I want to track individually few boolean fields such as when the work started? when the work delivered etc. here is my
models.py
class CustomerProject(models.Model):
project_title = models.CharField(max_length=2000,blank=True,null=True)
project_updated_at = models.DateTimeField(auto_now= True,blank=True,null=True)
#I want to track separately those BooleanField
project_started = models.BooleanField(default=True)
wting_for_sample_work = models.BooleanField(default=False)
sample_work_done = models.BooleanField(default=False)
working_on_final_project = models.BooleanField(default=False)
project_deliverd = models.BooleanField(default=False)
project_closed = models.BooleanField(default=False)
I think there might be three solutions for this.
First one is using simple history library.
https://django-simple-history.readthedocs.io/en/latest/
It creates a history model for your model and keeps track of all changes. This way, you can check which field is modified when, or go back to that state easily. But if you only want to keep track of the time which this booleans are set to True, this might be an overkill.
Second option would be to add a JSONField to keep track a time for any field you want.
Would be something like that.
{
"project_started": "2021-08-01 15:18:31",
"wting_for_sample_work": "2021-08-03 15:18:31"
}
You can set it in your view (by checking if each field is changed).
Third option would be just change these booleans to DateTimeField.
Then, you can check those datetime fields. If it is set, it is true and vice versa.
I think easiest is to go with 3rd option.
I have the following model:
class Site(models.Model):
"""
Model for a site entry
#author: Leonardo Pessoa
#since: 05/09/2016
"""
from decimal import Decimal
consolidated_financials = models.BooleanField(blank=True)
type = models.ForeignKey(Type)
tier1_business = models.ForeignKey(Business, limit_choices_to = {'tier': 1}, related_name='%(class)s_tier1')
Note that the consolidated_financials field has now the blank=True statement.
This was newly included. When I ran makemigrations, it didn't get the change, but when I add to finance_manager_sso it worked normally.
Is there a restriction with the Boolean field specifically?
Thanks
BooleanField does not take null=True, instead, use NullBooleanField.
There is a great answer on Programmers.se by Jacob Maristany that explains the reasoning behind this well
By allowing nulls in a boolean field, you are turning an intended binary representation (true/false) into a tri-state representation (true, false, null) where your 'null' entries are indeterminate.
For the full discussion, see Should I store False as Null in a boolean database field?
The blank parameter is not used by BooleanField. Instead, it is hard-coded to True. Passing blank=False has no effect, so the migration autodetector doesn't detect any changes to the field, and doesn't create any migrations.
Since the blank parameter is used by IntegerField, passing in blank=False will lead to a change in the serialized field. The migration autodetector will detect that change and create a migration (even though that change doesn't affect the database).
How come my "date" field doesn't come up in the admin system?
In my admin.py file i have
from django.contrib import admin
from glasses.players.models import *
admin.site.register(Rating)
and the Rating model has a field called "date" which looks like this
date = models.DateTimeField(editable=True, auto_now_add=True)
However within the admin system, the field doesn't show, even though editable is set to True.
Does anyone have any idea?
If you really want to see date in the admin panel, you can add readonly_fields in admin.py:
class RatingAdmin(admin.ModelAdmin):
readonly_fields = ('date',)
admin.site.register(Rating,RatingAdmin)
Any field you specify will be added last after the editable fields. To control the order you can use the fields options.
Additional information is available from the Django docs.
I believe to reason lies with the auto_now_add field.
From this answer:
Any field with the auto_now attribute
set will also inherit editable=False
and therefore will not show up in the
admin panel.
Also mentioned in the docs:
As currently implemented, setting
auto_now or auto_now_add to True will
cause the field to have editable=False
and blank=True set.
This does make sense, since there is no reason to have the field editable if it's going to be overwritten with the current datetime when the object is saved.
Major Hack:
If you really need to do this (as I do) you can always hack around it by immediatley setting the field to be "editable" defining the field as follows:
class Point(models.Model):
mystamp=models.DateTimeField("When Created",auto_now_add=True)
mystamp.editable=True
This will make the field editable, so you can actually alter it. It seems to work fine, at least with the mysql backing engine. I cannot say for certian if other backing stores would make this data immutable in the database and thus cause a problem when editing is attempted, so use with caution.
Depending on your specific needs, and any nuances in difference in behavior, you could do the following:
from django.utils.timezone import now
class MyModel(models.Model):
date = models.DateTimeField(default=now)
The default field can be used this way: https://docs.djangoproject.com/en/dev/ref/models/fields/#default
The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.
This does not set editable to False
It might have to do with the auto_now_add being true. Perhaps instead of that parameter to capture the date on add, you could override the model save method to insert the datetime when the id is null.
class Rating(models.Model):
....
def save(self, *args, **kwargs)
if not self.id:
self.date = datetime.datetime.now()
If you want any field to be visible in the list of all your entries (when you click on a model in the admin people) and not when you open that particular entry then -
class RatingAdmin(admin.ModelAdmin):
list_display = ('name', 'date')
admin.site.register(Rating, RatingAdmin)
'name' being your main field or any other field you want to display in the admin panel.
This way you can specify all the columns you want to see.
Can be displayed in Django admin simply by below code in admin.py
#admin.register(model_name)
class model_nameAdmin(admin.ModelAdmin):
list_display = ['date']
Above code will display all fields in django admin that are mentioned in list_display, no matter the model field is set to True for auto_now attribute
You can not do that, check the documentation
auto_now and auto_now_add are all non-editable fields and you can not override them...
I wanted to create an editable time field that defaults to the current time.
I actually found that the best option was to avoid the auto_now or auto_add_now altogether and simply use the datetime library.
MyTimeField = models.TimeField(default=datetime.now)
The big thing is that you should make it's the variable now instead of a function/getter, otherwise you're going to get a new default value each time you call makemigrations, which will result in generating a bunch of redundant migrations.
This is a combination of the answers by Hunger and using a decorator as suggested by Rahul Kumar:
In your admin.py, you just need:
#admin.register(Rating)
class RatingAdmin(admin.ModelAdmin):
readonly_fields = ('date',)
The fields specified in readonly_fields will appear in the add and change page i.e. inside the individual record. And - of course - are not editable.
The fields in list_display will constitute the representation in the main list page of the admin (i.e. the list of all records). In this case, it makes sense not to specify list_display = ('date',) only, because you will see only the dates. Instead, include also the main title / name of the record.
Example:
readonly_fields = ('title', 'date',)
if in the models.py this model is defined as:
class Rating(models.Model):
title = models.CharField('Movie Title', max_length=150)
...
date = models.DateTimeField(editable=True, auto_now_add=True)
def __str__(self):
return self.title
I have the two models shown below:
class EntryImage(models.Model):
image = models.ImageField(upload_to="entries")
class Entry(models.Model):
code = models.CharField(max_length=70, unique=True)
images = models.ManyToManyField(EntryImage, null=True, blank=True)
As you can see, Entry can have 0 or more images.
My question is: Is it possible to have that kind of
schema and dynamically change the upload_to based on the Entry code?
Well without going too far off, you could make an intermediary M2M table EntryImageDir with the directory name in it. You would link your EntryImages there with a foreign key and you could create the EntryImageDir either with a signal on Entry create or when uploading something.
The documentation for M2M with custom fields is here:
http://www.djangoproject.com/documentation/models/m2m_intermediary/
You can make upload_to a callable, in which case it will be called and passed the instance of the model it is on. However, this may not have been saved yet, in which case you may not be able to query the Entry code.