Question

Currently in our database the date field is entered as a string (ex: 11/7/2009). Is there anyway in my models.py file to convert this field from say a TextField to DateField so that in the Admin Console a user could select the date from the calendar view instead of having to enter it in manually? Perhaps parse it on the fly?

date = models.TextField()

convert to..

date = models.DateField()
Was it helpful?

Solution

Your best bet is to start storing the data correctly. In order to do this you'll want to alter the table to add a new field (in the database) with the date type. Parse the existing date data from the charfield into this new field and then finally alter the table to drop the charfield and rename the the temporary date field appropriately

This process could be simplified by using django-south to manage the migrations. You'll need 3 migrations: schemamigration to add the temporary field, datamigration to convert the data, schemamigration to drop the old column and rename the new one.

You could try using a custom form in the admin...you might be able to force the conversion at runtime, but it's really not a great idea since you really should be storing data correctly. I've used custom forms before in the admin, but not for this so I can't be sure if it would work.

OTHER TIPS

After changing the column in MSSQL to type date we still were having the same issue. I should have also mentioned we were using pyodbc to help server our backend. The change we made was within the pyodbc code in the operation.py file. A type-except was added.

 def convert_values(self, value, field): 
    .......
  elif field and field.get_internal_type() == 'DateField':
        try:
            value = value.date() # extract date
       #ADDED THE FOLLOWING TO CATCH THE ERROR
        except AttributeError:
            value = datetime.datetime.strptime(value, '%Y-%m-%d').date() 

After we added this the django admin console was displaying the Calendar widget.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top