Reputation: 401
I want to save a string as time format to store it in the database for a django project,
Here's my utils.py
file:
import datetime
import re
import math
from django.utils.html import strip_tags
def count_words(text_string):
word_string = strip_tags(text_string)
matching_words = re.findall(r'\w+', word_string)
count = len(matching_words)
return count
def get_read_time(text_string):
count = count_words(text_string)
read_time_min = math.ceil(count/200.0) #Assuming 200 words per min Reading
read_time = str(datetime.timedelta(minutes=read_time_min))
return read_time
Here's the required portion of the models.py
file:
class Post(models.Model):
read_time = models.TimeField(null=True, blank=True)
Here's the required portion of the views.py file
:
class PostDetailView(DetailView):
model = Post
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(**kwargs)
texts = self.object.content
# print(texts)
read_time=get_read_time(texts)
# print(read_time)
Post.objects.create(read_time=datetime.strptime(read_time, "%H:%M:%S"))
return context
The Output format of the string is 0:02:00
this I want to save it in the database as datetime field.
But I am encountering this error:-
Exception Type: ValueError at /post/this-blog-contains-an-image-with-it/
Exception Value: 's' is a bad directive in format '%H:%MM:%ss'
Upvotes: 1
Views: 291
Reputation: 477437
A TimeField
[Django-doc] expects a time
object, not a datetime
object. You can make use of the .time()
method [Django-doc] to retrieve the time part:
class PostDetailView(DetailView):
model = Post
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(**kwargs)
texts = self.object.content
read_time=get_read_time(texts)
Post.objects.create(read_time=datetime.strptime(read_time, '%H:%M:%S').time())
return context
It is however rather odd to construct a string instead of returning the timedelta
part itself:
def get_read_time(text_string):
count = count_words(text_string)
read_time_min = math.ceil(count/200.0) #Assuming 200 words per min Reading
return datetime.timedelta(minutes=read_time_min)
Then you can use this timedelta to obtain the time:
class PostDetailView(DetailView):
model = Post
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(**kwargs)
texts = self.object.content
read_time=get_read_time(texts)
Post.objects.create(read_time=(datetime.datetime.min + read_time).time())
return context
It furthermore does not make sense to construct objects in the get_context_data
. A GET request is supposed to have no side-effects, so you should only make database changes for POST, PUT, PATCH, DELETE, etc. requests. Not in the get_context_data
.
Upvotes: 1