SQL Server Date Validatind Error When Trying To Migrate From sqllite to mssql in django

5w9g7ksd  于 2023-06-21  发布在  Go
关注(0)|答案(1)|浏览(121)
from django.db import models
from tinymce import models as tinymce_models
from django.core.exceptions import ValidationError
from django.utils import timezone
# Create your models here.

class Role(models.Model):
    roleName    = models.CharField(max_length=200)
    active      =models.BooleanField(default=True)
    createdBy   =models.CharField(max_length=200)
    modifiedBy  =models.CharField(max_length=200)
    createdat = models.DateTimeField(
        db_column='createdAt', blank=True, null=True, auto_now_add=True)
    updatedat = models.DateTimeField(
        db_column='updatedAt', blank=True, null=True, auto_now=True)
    
    class Meta:
        verbose_name_plural="Role"
    def __str__(self):
        return self.roleName
    
class CMSUser(models.Model):
    fullName    =models.CharField(max_length=200)
    email       =models.CharField(max_length=200)
    password    =models.CharField(max_length=200)
    active      =models.BooleanField(default=True)
    createdBy   =models.CharField(max_length=200)
    modifiedBy  =models.CharField(max_length=200)
    createdat = models.DateTimeField(
        db_column='createdAt', blank=True, null=True, auto_now_add=True)
    updatedat = models.DateTimeField(
        db_column='updatedAt', blank=True, null=True, auto_now=True)
    
    class Meta:
        verbose_name_plural="User"

    def _str_(self):
        return self.fullName  

class Campus(models.Model):
    
    campusName = models.CharField(max_length=200,unique=True)
    createdat = models.DateTimeField(
        db_column='createdAt', blank=True, null=True, auto_now_add=True)
    updatedat = models.DateTimeField(
        db_column='updatedAt', blank=True, null=True, auto_now=True)
    class Meta:
         verbose_name_plural="Campus"
    def __str__(self):
        return self.campusName 

class Group(models.Model):
    groupName   =models.CharField(max_length=200)
    active      =models.BooleanField(default=True)
    createdBy   =models.CharField(max_length=200)
    modifiedBy  =models.CharField(max_length=200)
    createdat = models.DateTimeField(
        db_column='createdAt', blank=True, null=True, auto_now_add=True)
    updatedat = models.DateTimeField(
        db_column='updatedAt', blank=True, null=True, auto_now=True)
    
    class Meta:
        verbose_name_plural="Group"

    def __str__(self):
        return self.groupName
    

class Menu(models.Model):
    menuName    =models.CharField(max_length=200)
    active      =models.BooleanField(default=True)
    createdBy   =models.CharField(max_length=200)
    modifiedBy  =models.CharField(max_length=200)
    createdat = models.DateTimeField(
        db_column='createdAt', blank=True, null=True, auto_now_add=True)
    updatedat = models.DateTimeField(
        db_column='updatedAt', blank=True, null=True, auto_now=True)

    class Meta:
        verbose_name_plural="Menu"
        
    def _str_(self):
        return self.menuName

class Content(models.Model):
    contentTitle    =models.CharField(max_length=200)
    contentImage    =models.ImageField(upload_to='upload/content/')
    contentData     =tinymce_models.HTMLField()
    menuID          =models.ForeignKey(Menu, on_delete=models.CASCADE)
    active          =models.BooleanField(default=True)
    createdBy       =models.CharField(max_length=200)
    modifiedBy      =models.CharField(max_length=200)
    createdat       =models.DateTimeField(db_column='createdAt', blank=True, null=True, auto_now_add=True)
    updatedat       =models.DateTimeField(db_column='updatedAt', blank=True, null=True, auto_now=True)

    class Meta:
        verbose_name_plural="Content"

    def _str_(self):
        return self.contentTitle 

class UserRole(models.Model):
    
    roleID = models.ForeignKey(Role, on_delete=models.CASCADE)
    cmUserID = models.ForeignKey(CMSUser, on_delete=models.CASCADE)
    createdat = models.DateTimeField(
        db_column='createdAt', blank=True, null=True, auto_now_add=True)
    updatedat = models.DateTimeField(
        db_column='updatedAt', blank=True, null=True, auto_now=True)
    
    class Meta:
         verbose_name_plural="UserRole"

class UserGroup(models.Model):
    
    groupID = models.ForeignKey(Group, on_delete=models.CASCADE)
    cmUserID = models.ForeignKey(CMSUser, on_delete=models.CASCADE)
    createdat = models.DateTimeField(
        db_column='createdAt', blank=True, null=True, auto_now_add=True)
    updatedat = models.DateTimeField(
        db_column='updatedAt', blank=True, null=True, auto_now=True)
    
    class Meta:
         verbose_name_plural="UserGroup"

class GroupMenu(models.Model):
    
    groupID = models.ForeignKey(Group, on_delete=models.CASCADE)
    menuID = models.ForeignKey(Menu, on_delete=models.CASCADE)
    createdat = models.DateTimeField(
        db_column='createdAt', blank=True, null=True, auto_now_add=True)
    updatedat = models.DateTimeField(
        db_column='updatedAt', blank=True, null=True, auto_now=True)
    
    class Meta:
         verbose_name_plural="GroupMenu"


    



class ParentDepartment(models.Model):
    
    departmentName = models.CharField(max_length=200,unique=True)
    departmentShortName = models.CharField(max_length=200,unique=True)
    campusId = models.ForeignKey(Campus, on_delete=models.CASCADE)
    createdat = models.DateTimeField(
        db_column='createdAt', blank=True, null=True, auto_now_add=True)
    updatedat = models.DateTimeField(
        db_column='updatedAt', blank=True, null=True, auto_now=True)
    
    class Meta:
         verbose_name_plural="ParentDepartment"
    def __str__(self):
        return self.departmentName
    

class ChildDepartment(models.Model):
    
    departmentName = models.CharField(max_length=200,unique=True)
    departmentShortName = models.CharField(max_length=200,unique=True)
    parentDepartment = models.ForeignKey(ParentDepartment, on_delete=models.CASCADE)
    deptDescription =tinymce_models.HTMLField(null=False, blank=False,default='N/A')
    createdat = models.DateTimeField(
        db_column='createdAt', blank=True, null=True, auto_now_add=True)
    updatedat = models.DateTimeField(
        db_column='updatedAt', blank=True, null=True, auto_now=True)
    
    class Meta:
         verbose_name_plural="ChildDepartment"
    def __str__(self):
        return self.departmentName 

class Jobs(models.Model):
    
    jobTitle       =models.CharField(max_length=200)
    # jobImage    =models.ImageField(upload_to='upload/jobs/',blank=False, null=False, default='')
    jobDescription =tinymce_models.HTMLField()
    jobActive      =models.BooleanField(default=True)
    createdat = models.DateTimeField(
        db_column='createdAt', blank=True, null=True, auto_now_add=True)
    updatedat = models.DateTimeField(
        db_column='updatedAt', blank=True, null=True, auto_now=True)
    expiration_date = models.DateTimeField(max_length=100, blank=False, null=False, default='')

    
    class Meta:
         verbose_name_plural="Jobs"
    def _str_(self):
        return self.jobTitle 
    def clean(self):
        if self.expiration_date <= timezone.now():
            raise ValidationError("Expiration date must be greater than the current date.")
    def save(self, *args, **kwargs):
        self.clean()  # Run the clean method before saving
        super().save(*args, **kwargs)



class NewUpdates(models.Model):
    
    newsTitle       =models.CharField(max_length=200)
    newsContent =tinymce_models.HTMLField()
    newsActive      =models.BooleanField(default=True)
    titleImage = models.ImageField(upload_to='upload/newupdates/')
    createdat = models.DateTimeField(
        db_column='createdAt', blank=True, null=True, auto_now_add=True)
    updatedat = models.DateTimeField(
        db_column='updatedAt', blank=True, null=True, auto_now=True)
    expiration_date = models.DateTimeField(max_length=100, blank=False, null=False, default='')

    
    class Meta:
         verbose_name_plural="NewsUpdates"
    def _str_(self):
        return self.newsTitle 
    def clean(self):
        if self.expiration_date <= timezone.now():
            raise ValidationError("Expiration date must be greater than the current date.")
    def save(self, *args, **kwargs):
        self.clean()  # Run the clean method before saving
        super().save(*args, **kwargs)



class StudentNoticeBoard(models.Model):
    
    # contents =tinymce_models.HTMLField()
    Image    =models.ImageField(upload_to='upload/noticeboard/',blank=False, null=False, default='')
    createdat = models.DateTimeField(
        db_column='createdAt', blank=True, null=True, auto_now_add=True)
    updatedat = models.DateTimeField(
        db_column='updatedAt', blank=True, null=True, auto_now=True)
    expiration_date = models.DateTimeField(max_length=100, blank=False, null=False, default='')

    class Meta:
         verbose_name_plural="StudentNoticeBoard"
 
    def clean(self):
        if self.expiration_date <= timezone.now():
            raise ValidationError("Expiration date must be greater than the current date.")
    def save(self, *args, **kwargs):
        self.clean()  # Run the clean method before saving
        super().save(*args, **kwargs)



    
class Events(models.Model):
    
    # contents =tinymce_models.HTMLField()
    Image    =models.ImageField(upload_to='upload/events/',blank=False, null=False, default='')
    createdat = models.DateTimeField(
        db_column='createdAt', blank=True, null=True, auto_now_add=True)
    updatedat = models.DateTimeField(
        db_column='updatedAt', blank=True, null=True, auto_now=True)
    expiration_date = models.DateTimeField(max_length=100, blank=False, null=False, default='')

    class Meta:
         verbose_name_plural="Events"
   
    
    def clean(self):
        if self.expiration_date <= timezone.now():
            raise ValidationError("Expiration date must be greater than the current date.")
    def save(self, *args, **kwargs):
        self.clean()  # Run the clean method before saving
        super().save(*args, **kwargs)

    
class Tender(models.Model):
    
    # contents =tinymce_models.HTMLField()
    Image    =models.ImageField(upload_to='upload/tender/',blank=False, null=False, default='')
    createdat = models.DateTimeField(
        db_column='createdAt', blank=True, null=True, auto_now_add=True)
    updatedat = models.DateTimeField(
        db_column='updatedAt', blank=True, null=True, auto_now=True)
    expiration_date = models.DateTimeField(max_length=100, blank=False, null=False, default='')

    class Meta:
         verbose_name_plural="Tender"
    
    def clean(self):
        if self.expiration_date <= timezone.now():
            raise ValidationError("Expiration date must be greater than the current date.")
    def save(self, *args, **kwargs):
        self.clean()  # Run the clean method before saving
        super().save(*args, **kwargs)
    

class CampusGroups(models.Model):
    
    campus =models.ForeignKey(Campus, on_delete=models.CASCADE)
    group =models.ForeignKey(Group, on_delete=models.CASCADE)
    createdat = models.DateTimeField(
        db_column='createdAt', blank=True, null=True, auto_now_add=True)
    updatedat = models.DateTimeField(
        db_column='updatedAt', blank=True, null=True, auto_now=True)
    

class FacultyProfiles(models.Model):
    
    name       =models.CharField(max_length=200)
    Image    =models.ImageField(upload_to='upload/faculty/')
    designation= models.CharField(max_length=200)
    jouralPublications= models.IntegerField()
    conferencePublications= models.IntegerField()
    address       =models.CharField(max_length=200)
    phone = models.CharField(max_length=200)
    mobile = models.CharField(max_length=200)
    fax = models.CharField(max_length=200)
    email = models.CharField(max_length=200)
    description =tinymce_models.HTMLField()
    
    createdat = models.DateTimeField(
        db_column='createdAt', blank=True, null=True, auto_now_add=True)
    updatedat = models.DateTimeField(
        db_column='updatedAt', blank=True, null=True, auto_now=True)

    class Meta:
         verbose_name_plural="Faculty"
    def _str_(self):
        return self.name

Above is the code for my model. The following is the error that I am facing.

Operations to perform:
  Apply all migrations: MasterUser, admin, auth, contenttypes, sessions
Running migrations:
  Applying MasterUser.0010_alter_events_expiration_date_and_more...Traceback (most recent call last):
  File "C:\Users\Qamar\Desktop\ContentManagementSystem\manage.py", line 22, in <module>
    main()
  File "C:\Users\Qamar\Desktop\ContentManagementSystem\manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
    utility.execute()
  File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 413, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 398, in execute
    output = self.handle(*args, **options)
  File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 89, in wrapped
    res = handle_func(*args, **kwargs)
  File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle
    post_migrate_state = executor.migrate(
  File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards     
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration
    state = migration.apply(state, schema_editor)
  File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\migration.py", line 126, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\operations\fields.py", line 244, in database_forwards
    schema_editor.alter_field(from_model, from_field, to_field)
  File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\schema.py", line 594, in alter_field
    self._alter_field(model, old_field, new_field, old_type, new_type,
  File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\mssql\schema.py", line 461, in _alter_field
    new_default = self.effective_default(new_field)
  File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\schema.py", line 310, in effective_default        
    return field.get_db_prep_save(self._effective_default(field), self.connection)
  File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 842, in get_db_prep_save       
    return self.get_db_prep_value(value, connection=connection, prepared=False)
  File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 1427, in get_db_prep_value     
    value = self.get_prep_value(value)
  File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 1406, in get_prep_value        
    value = super().get_prep_value(value)
  File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 1266, in get_prep_value        
    return self.to_python(value)
  File "C:\Users\Qamar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 1388, in to_python
    raise exceptions.ValidationError(
django.core.exceptions.ValidationError: ['“” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']

help me in resolving this problem

yh2wf1be

yh2wf1be1#

In your Events model, this line has a problem...

expiration_date = models.DateTimeField(max_length=100, blank=False, null=False, default='')

The default value is an empty string. However, blank=False explicitly disallows saving with an empty string in the field. In a migration, you're copying over records, which is basically creating them new elsewhere, so their field limitations apply when they get saved. Here you are breaking your saving requirements when copying records with no expiration_date.

Currently your field is not allowed to be blank (eg, an empty field on a form) or Null (an empty field in a database). To handle the records that don't currently have an entry for them during a migration you could:

  • You could set blank=True for the duration of your migration
  • You could change the default to None and set null=True during the migration
  • Or you could set the default to be an explicit time, like datetime.now(), or a string as formatted in the error message: YYYY-MM-DD HH:MM

相关问题