On refresh I want this to reset to default
from_date = models.DateField(default='2000-01-01')
Status = models.CharField(choices=A_K, max_length=100, default='no Status')
to_date = models.DateField(default='2000-01-01')
right now I have default when something new is created, while it is fine, I need it to be set to default if page is refreshed or field is null(Im happy with any solution).
I read here:
Django - How to reset model fields to their default value?
that it is possible with none like with null=true and blank=true, but that didnt worked.
Do I really need a whole function for that ?
Related
When I am trying to run python3 manage.py makemigrations it shows :
You are trying to add a non-nullable field 'topic_id' to journey_template without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option:
enter code here
from django.db import models
class Topic_Table(models.Model):
topic_id=models.IntegerField(primary_key=True)
topic_name = models.CharField(max_length=100, blank=True)
weightage = models.CharField(max_length=15, blank=True)
grade = models.IntegerField( null=True)
subject = models.CharField(max_length=100, blank=True)
sequence = models.IntegerField(null=True)
month = models.CharField(max_length=15, blank=True)
class Journey_template(models.Model):
student_id = models.IntegerField(default=1)
topic_id = models.ForeignKey('Topic_Table',on_delete=models.CASCADE)
subtopic_id = models.IntegerField()
journey_template_key = models.IntegerField(primary_key=True)
How would I fix this?
You are adding the topic_id field on Journey_template model.
This model already has data on your database.
You have a few options:
1 - provide a default value (like entering the number 1)
2 - delete your database and start with a fresh migration
If you table already has data, adding a non-nullable column without any default will violate the non-null constraint. Django migration doesn't check the table for data, so it assumes there is some.
If your table has no rows, you can go ahead and give it any legal default value. The default does not change your model, it just gives Django a value it can fill in. Since there are no rows of data in the table, it will have no effect other than to make Django happy.
If you table has rows, then if you can think of a sensible value to populate the existing rows with, then use it. Your other option is to change the model by adding null=True to the field and Django will just put nulls in that field for existing rows. (Later, you can put your own values in to those fields with Django or other methods and change the field back to null=False if you like. You will get the same question when you migrate but the answer will have no effect if the fields are not null). null=False is the default for any field in your model.
I am using Django-Jet and have a model with many ForeignKey fields. For those fields I want their values retrieved dynamically via AJAX and not preloaded. One of the field is like this:
class Person(Base_Entity):
first_name = models.ForeignKey(
'Name',
null = True,
blank = True,
default = None,
verbose_name = _('first name of person'),
on_delete = models.SET_NULL,
related_name = 'is_first_name_of_%(app_label)s_%(class)s',
)
)
#staticmethod
def autocomplete_search_fields():
return 'first_name__name',
(The Name model has hundreds of entries, and there will be even more later)
It seems I cannot set that field to NULL in Django Admin (no line with dashes appears):
If I turn on autocomplete (i.e. remove the autocomplete_search_fields method), I do get that NULL entry, BUT I also get all the possible values preloaded in the HTML select, and that slows down the page loading to a point it is not usable.
I am using Django 2.1.4, Django-Jet 1.0.8 (I suspect the issue is closely related to Django-Jet)
Any help is appreciated.
I am using djangojet and this relation shows an empty value choice in admin ("-----"):
someModel_FK= models.ForeignKey(someModel,
related_name='this-model',
null=True,
blank=True,
on_delete=models.SET_NULL)
a - Remove django-jet and check on default admin.
b- Are you missing migrations ? is this "null=True,blank=True, " migrated to DB ?
I want to know if there is a way programmatically of finding the default assigned to a field on any model, I have the model instance and the field names.
In the below model I would have to get the default from u_value, allow_profile and disabled if they are Null to be able to save the data correctly. The Database is Firebird
Eg model:
class Fitting(models.Model):
uuid = UUIDField(primary_key=True)
bought_in_control_panel_file = models.ForeignKey(BoughtInControlPanelFile, db_column='bought_in_control_panel_file_id',null=True, blank=True)
name = models.CharField(_('name'),null=True, blank=False,max_length=255)
code = models.CharField(_('Code'),null=True, blank=True,max_length=255)
fire_rating = models.ForeignKey(FireRating, db_column='fire_rating_id',null=True, blank=True)
u_value = models.FloatField(_('U-value'),default=0)
acoustic_rating = models.FloatField(_('Acoustic Rating'),default=0)
allow_profile = models.BooleanField(default=0)
disabled = models.BooleanField(default=0)
date_time_updated = models.DateTimeField(null=True, blank=True, auto_now=True)
model_field.get_default() returns the default assigned to a model field
Example:
model = Polls.objects.all()
for model_field in model:
print model_field.get_default()
Django will automatically save the model instance with default values when you save it and haven't set the required non-null fields.
Doesn't your object saved in DB with default values when they are not set explicitly?
The value for default property can be a function which will be called when new object will be saved. You may want to try that too.
Is there a Djangotastic way to display a default value for a field in the admin when there isn't a value? Like 'n/a', but not to save that to the database?
When I set all the fields in the model below to readonly in the admin, the front-end display looks like the image at the bottom. It feels visually collapsed like it should have a value or a box or something. If there isn't an easy way to do what I am looking for, then is there another solution to make the front-end admin more clear for the user?
class Package(models.Model):
packaging_format = models.CharField(max_length=40)
package_delivery_pattern = models.CharField(max_length=30, blank=True)
package_delivery_comments = models.CharField(max_length=250, blank=True)
package_manifest_filename = models.CharField(max_length=50)
package_description = models.CharField(max_length=250, blank=True)
package_naming_pattern = models.CharField(max_length=50)
Screenshot of fields as displayed in the admin:
What's happening is that your actually saving a empty string '' in your CharFields instead of None values (because of the blank=True). So the Django-admin is showing the string you saved in the db (in this case, nothing).
If you change your CharFields to null=True instead of blank=True, you will be saving NULL in your database instead of an empty string. And that way, you will get the behaviour you want.
EDIT: I know this solution is not recommended (following Django Docs), but that's the behaviour you wanted. Django-admin is just showing you the string you have in the database, which is ''.
Another solution that comes to my mind is to modify the ModelAdmin for your Package model, something like:
class PackageAdmin(admin.ModelAdmin):
readonly_fields = ['show_package_delivery_pattern', ...]
def show_package_delivery_pattern(self, obj):
if obj.package_delivery_pattern:
return obj.package_delivery_pattern
else:
return 'N/A'
# same with all your CharFields..
As of Django 1.9 you can use empty_value_display at the site, model, or field level in the Django admin. At the model level:
class YourModelAdmin(admin.ModelAdmin):
empty_value_display = '---'
I have a problem when I update an object. This is the model:
class HourRecord(models.Model):
day_of_work = models.PositiveIntegerField(max_length=1)
date_of_work = models.DateField(verbose_name='creation date')
who_worked = models.ForeignKey(User)
project = models.ForeignKey(Project, related_name='hour_record_set', null=True)
created_by = models.ForeignKey(User, editable=False, related_name='hour_record_creator')
created = models.DateTimeField(auto_now_add=True, editable=False, verbose_name='creation date')
modified_by = models.ForeignKey(User, editable=False, related_name='hour_record_modifier')
modified = models.DateTimeField(auto_now=True, editable=False)
def save(self, request):
if not self.id:
self.who_worked = request.user
self.created_by = request.user
self.modified_by = request.user
super(HourRecord, self).save()
The created_by field should only be set if its a new object. Therefore the "if not self.id:". This worked fine till now.
Till now I updated the object like this:
if hrform.is_valid():
hour_record = hrform.save(commit=False)
hour_record.save(request)
But when I update the model like this I get an error:
project = Project.objects.get(id=project_pk)
hr_object = HourRecord(id=hour_record_pk, day_of_work=weekday, date_of_work=date, who_worked=request.user, project=project)
hr_object.save(request)
The error message is:
Column 'created_by_id' cannot be null
Thats strange to me since the created_by column has been already set. I checked it in the database. After this error message when I check again the object is updated and created_by_id is set to null. Actually this is strange. I get an error message + the row is updated.
The second approach is called from within a json data handling view. But I don't think that it has anything to do with it. I think I can circumvent this problem when I reset the created_by_id, but that is not what I want to do, since it corrupts the logic of this created_by field.
Well, the issue appears to be that you are explicitly setting the id field when you instantiate the HourRecord object:
hr_object = HourRecord(id=hour_record_pk,...
So when you get to the save() method, it checks if it has an ID... and it does, so it doesn't set who_worked and created_by.
I wonder why you need to set the ID. Normally, you should let the database set it automatically via the autoincrement.
(Not related to your issue, but your save method should accept the force_update and force_insert parameters, and pass them to the super method. The easiest way to do this is to get into the habit of always using *args, **kwargs when overriding a method.)
Edit: To answer your question of why this doesn't work like an update statement, it's because you're explicitly replacing the old object with a new one. In effect, you're deleting the old db entry and inserting a completely new set of data. There'd be no way for Python to know whether you intended to keep a field's old value, or set it to NULL, for example.
The way to do this, as you have noted, is to get the existing object and updating its attributes explicitly.