Home > Blockchain >  How can I solve strftime TypeError when making a POST request in Django?
How can I solve strftime TypeError when making a POST request in Django?

Time:10-23

I am creating an API that contains a DateTimeField using Django but I am getting the following error "TypeError: descriptor 'strftime' for 'datetime.date' objects doesn't apply to a 'str' object" I have tried checking different sources but I haven't found a solution.

  • The error is arising from the start_date line.
from datetime import datetime

def question_view(request):
    if request.method == 'GET':
        return HttpResponse("Вопрос не создан")
    elif request.method == 'POST':
        poll_question = request.POST['poll_question']
        title = request.POST['title']
        start_date = datetime.strftime(request.POST['start_date'],'%Y-%m-%d')
        Question.objects.create(poll_question=poll_question,title=title, start_date=start_date)
        return HttpResponse("Вопрос создан")
    else:
        return "Попробуйте снова"

CodePudding user response:

I think an easy way to fix this is to convert the object to a string according to a given format using datetime.strptime as stated in the doc

Your view will now be written as:

from datetime import datetime

def question_view(request):
    if request.method == 'GET':
        return HttpResponse("Вопрос не создан")
    elif request.method == 'POST':
        poll_question = request.POST['poll_question']
        title = request.POST['title']
        start_date = datetime.strptime(request.POST['start_date'],'%Y-%m-%d')
        Question.objects.create(poll_question=poll_question,title=title, start_date=start_date)
        return HttpResponse("Вопрос создан")
    else:
        return "Попробуйте снова"

strptime Parse a string into a datetime object given a corresponding format. (As per the datetime documentation)

  • Related