Type Object 'datetime.datetime' has no attribute 'datetime'

Asked

Viewed 168 times

-2

I have a view that matters some functions of a model, and when I import the model within the view, I have a problem with datetime. The function that exists in the model works perfectly, but in the view I have error. The best_month function is :

    def best_month(cls):
        res = {}
        month_price = cls.objects.values_list('created_time__month').annotate(total=Sum('price'))
        if month_price:
            res['month'], res['price'] = max(month_price, key=lambda i: i[1])
            res['month_name'] = date(datetime.date(datetime.datetime.now().year, month=res['month'], day=1), 'F')
        return res

but when I call to view :

    
def dashboard(request):
    context = {'segment': 'index'}
    html_template = loader.get_template('account/dashboard.html')

    context.update(dict(Item.total_info()))
    context['best_month'] = Item.best_month()
    context['orders_month_report'], context['orders_month_report_labels'] = Item.orders_month_report()

    context['orders'], context['info'] = set_pagination(request, Item.objects.all().order_by('-id'), item_numer=10)
    if not context['orders']:
        messages.warning(request, context['info'])
    return HttpResponse(html_template.render(context, request))
Tenho o seguinte erro : 
    
---> 71             res['month_name'] = date(datetime.date(datetime.datetime.now().year, month=res['month'], day=1), 'F')
     72         return res
     73

AttributeError: type object 'datetime.datetime' has no attribute 'datetime'

1 answer

0

Talk Chuck! All right?

I couldn’t find in your code which import you are performing inside the datetime library. I believe the error is in the confusion of the module name.

To use the datetime.datetime, you can:

>>> import datetime
>>> date = datetime.datetime(2021, 4, 23) 
>>> print(date)
2021-04-23 00:00:00

As parameters, it is possible to use datetime.datetime(ano, mes, dia, hora, minuto, segundo, microsegundo, e info).

  • True, well remembered. I imported in models as python
from datetime import datetime, date
 and in the views I imported as 
import datetime 


Browser other questions tagged

You are not signed in. Login or sign up in order to post.