Home > Blockchain >  How to create datefield in django models in the format (mm-dd-yyyy)
How to create datefield in django models in the format (mm-dd-yyyy)

Time:11-01

I am scraping the dates from different websites and it is in the format of mm-dd-yyyy ie. 10-28-2021 . Right now, I'm storing it as a string.

In django models, I have created the field as:

issued = models.CharField(max_length=16)

This stores the date as string.

But I want to convert into a datefield.

When I tried,

issued = models.DateField()

I cannot store the date in this field.

How to add the date in the particular format in the above field?

After solution,

The Traceback is :

Environment:


Request Method: GET
Request URL: http://localhost:8000/

Django Version: 3.1.5
Python Version: 3.8.5
Installed Applications:
['grappelli',
 'filebrowser',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'dibbs_spider',
 'userapp']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']


Template error:
In template C:\Users\admin\PycharmProjects\spider\templates\Partsbase-data-table (1).html, error at line 295
   month must be in 1..12
   285 :                            <th>Issued</th>
   286 :                            <th>Return by</th>
   287 : <!--                           <th>Est. Value</th>-->
   288 : <!--                           <th>Days</th>-->
   289 : <!--                           <th>Status</th>-->
   290 : <!--                           <th>Match Details</th>-->
   291 :                            <th>Download</th>
   292 :                        </tr>           
   293 :                    </thead>
   294 :                    <tbody>
   295 :                         {% for i in dibbs %} 
   296 :                        <tr>
   297 :                            <!-- <td data-label="#">{{ i.hash}}</td> -->
   298 :                            <td data-label="NSN/Part Number">{{ i.nsn }}</td>
   299 :                            <td data-label="Nomenclature">{{ i.nomenclature }}</td>
   300 :                            <td data-label="Technical Documents">{{ i.technical_documents }}</td>
   301 :                            <td data-label="solicitation">{{ i.solicitation }}</td>
   302 :                            <td data-label="status">{{ i.status }}</td>
   303 :                            <td data-label="purchase_request">{{ i.purchase_request }}</td>
   304 :                            <td data-label="issued">{{ i.issued|date:"m-d-Y" }}</td>
   305 :                            <td data-label="Return by">{{ i.return_by|date:"m-d-Y" }}</td>


Traceback (most recent call last):
  File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\admin\PycharmProjects\spider\dibbs_spider\views.py", line 25, in bids
    return render(request,'Partsbase-data-table (1).html',context)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\shortcuts.py", line 19, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\backends\django.py", line 61, in render
    return self.template.render(context)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 170, in render
    return self._render(context)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 162, in _render
    return self.nodelist.render(context)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 938, in render
    bit = node.render_annotated(context)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\defaulttags.py", line 168, in render
    len_values = len(values)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\paginator.py", line 143, in __len__
    return len(self.object_list)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 269, in __len__
    self._fetch_all()
  File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 1308, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 53, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1156, in execute_sql
    cursor.execute(sql, params)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 98, in execute
    return super().execute(sql, params)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 66, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
    return Database.Cursor.execute(self, query, params)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\sqlite3\dbapi2.py", line 64, in convert_date
    return datetime.date(*map(int, val.split(b"-")))

Exception Type: ValueError at /
Exception Value: month must be in 1..12

CodePudding user response:

You can change input format of date in settings.py like this:

DATE_INPUT_FORMATS = ['%m-%d-%Y']

Here's official Django doc: link

CodePudding user response:

Convert the string into Date time object using strptime,

from datetime import datetime    
date_time_str = '10-28-2021'

date1 = datetime.strptime(date_time_str, "%m-%d-%Y")
print(date1)

EDIT1 : If you want it without the time ,

from datetime import datetime    
date_time_str = '10-28-2021'

date1 = datetime.strptime(date_time_str, "%m-%d-%Y").date()
print(type(date1))
  • Related