I have created a model like this,
class fleets(models.Model):
fleet_id = models.IntegerField(primary_key=True)
fleet_name = models.CharField(max_length=20)
description = models.CharField(max_length=40, null=True)
And when I observe in the postgresql admin the table I see is like what I want,
fleet_id as pk and not null
fleet_name not null
description null
But, why when I want to add some fleet with the django-admin it says is not possible? I forget some parameter?
Thank you very much!!
When adding a field to your model and specifying null=True you are saying that field can be null. For fleet_idand fleet_name, these cannot be null since you have not specified null=True so they are Not Null.
For the django-admin, the docs specify to avoid null=True on CharField. What you want here is blank=True instead of null=True.
See the docs here.
models.CharField(blank=True) # No problem, blank is stored as ''
models.CharField(null=True) # NULL allowed, but will never be set as NULL
Related
I have added a new model to my admin. This is my models.py:
class EngineeringToolAttributeType(models.Model):
name = models.CharField(max_length=50)
description = models.CharField(max_length=255, blank=True, null=True)
api_url = models.CharField(max_length=255, blank=True, null=True)
api_field = models.CharField(max_length=50, blank=True, null=True)
active = models.BooleanField(default=True)
def __str__(self):
return self.name
And the admin.py:
from extras.models import EngineeringToolAttributeType
from django.contrib import admin
class EngineeringToolAttributeTypeAdmin(admin.ModelAdmin):
fields = ['name', 'description', 'api_url', 'api_field', 'active']
list_display = ('name', 'description', 'api_url', 'api_field', 'active')
admin.site.register(EngineeringToolAttributeType, EngineeringToolAttributeTypeAdmin)
When I try to add (click on add button via the admin), I get this error:
Internal Server Error: /website/admin/extras/engineeringtoolattributetype/add/
IntegrityError at /admin/extras/engineeringtoolattributetype/add/
null value in column "name" violates not-null constraint
This has never happened before. I know name is not allowed to be Null, but I'm still adding a record. How is that possible?
This issue is partially result of not using CharField and TextField properly. You should almost never use null=True on this fields and their subclasses.
https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.Field.null
Avoid using null on string-based fields such as CharField and TextField. If a string-based field has null=True, that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it’s redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL. One exception is when a CharField has both unique=True and blank=True set. In this situation, null=True is required to avoid unique constraint violations when saving multiple objects with blank values.
I would highly suggest removing this param from yourCharFields and TextFields.
Also just to be sure run ./manage.py makemigrations && ./manage.py migrate.
This has a short answer here.
If you specify a field as not null field django will ask you to either provide a default value in code itself or it will ask you to provide a default value when you run migrations.
A better approach would be to provide some sane default in your models.py itself. After that run python manage.py makemigrations and python manage.py migrate. You should be fine.
So, that's the problem:
I currently have a model:
class UserData(models.Model):
avatar = models.ImageField(verbose_name='Avatar',upload_to='images/profile_pics',blank=True,null=True)
doc_type = models.CharField(verbose_name='Document type',max_length=1,default='0')
And a form:
class UserCreationForm(forms.ModelForm):
avatar = forms.ImageField(label='Avatar',required=False, error_messages = {'invalid':"Images only"}, widget=forms.FileInput)
class Meta:
model = UserData
So, the problem occurs when the user tries to edit his data. When no image is provided, the current image path in the db overwrites with the empty string. Is there any way to solve that problem?
avatar = models.ImageField(verbose_name='Avatar',upload_to='images/profile_pics',null=True)
removing blank=True should solve it
You can solve the problem by making image field required.
avatar = forms.ImageField(label='Avatar', required=True, error_messages={'invalid':"Images only"}, widget=forms.FileInput)
Remove both blank and null equal to True
blank=True
Allows the field to be empty
null=True
Allows the empty data to be saved in database
so you can choose which one will work for you the best.
I have a model with the following field
class Callstat(models.Model):
agentdisplayname = models.CharField(null=True, max_length=60, db_column='AgentDisplayName', blank=True)
class Meta:
db_table = u'callstat'
def __unicode__(self):
return u'%d: %s' % (self.callid, self.telnum)
However when I do the following,
call = Callstat.objects.all().filter(agentdisplayname__isnull=True)
MySQL's general_log shows the resulting SQL as
SELECT `callstat`.`AgentDisplayName` FROM `callstat` WHERE `callstat`.`AgentDisplayName` LIKE 'None';
The data in the database is added by a separate application and I have no control over the fact that it is leaving fields as NULL. I'm fairly certain this can't be a bug in Django so any help as to what I am doing wrong would be greatly appreciated.
EDIT: OK turns out I'd missed something further down in my code, and this filter had been overwritten by a __exact filter in a loop.
Set null=True on your column. By default null parameter it is set to false, which means NULL is not a permitted value.
agentdisplayname = models.CharField(null=True, max_length=60, db_column='AgentDisplayName', blank=True, null=True)
Probably you would need to change the existing db column as well.
I have following model:
class Client(models.Model):
user = models.OneToOneField(DjangoUser, unique=True)
address = models.ForeignKey(Address,blank=True)
class Address(models.Model):
(...)
Then I do:
client=Client()
client.address=address #any Address instance
client.save()
And now: how can I remove foreign association key from client?
client.address=None
seem not to work.
To be able to null out a foreign key, it's not enough to set in blank. You must also specify that null=True is also set on the field. See The Difference Between Blank and Null.
Your current models setup does not allow null=True, thus you cannot set it to None.
address = models.ForeignKey(Address,blank=True, null=True)
the key is null=True as well as blank=True
also, make sure to syncdb etc
This seems very basic and I must be missing something, but here goes anyways...
With two models like so:
class School(models.Model):
name = models.CharField("Official School Name", max_length=128)
address = models.TextField("Address of the School", max_length=256)
mascot = models.CharField("Name of the School Mascot", max_length=128)
class StudentProfile(models.Model):
name = models.CharField(max_length=128)
school = models.ForeignKey(School)
If the student gets created before the school, how do I give 'school' a default empty value? Is it blank or null or what?
Thanks!
null if you want the database to allow the relationship to be null, blank if you don't want the Django admin site to complain about it being null.
From the documentation on "blank":
"Note that this is different than null. null is purely database-related, whereas blank is validation-related. If a field has blank=True, validation on Django’s admin site will allow entry of an empty value. If a field has blank=False, the field will be required."
In short, you probably want both.