0

I want to change my datetime field but current_user_moneybooks has many objects.

so i want to know is there any method to change the format of datetime field.

I tried link:

for current_user_moneybook in current_user_moneybooks
   def start_date(self):
        return self.start_date.strftime("%Y-%m-%d")
    def end_date(self):
        return self.end_date.strftime("%Y-%m-%d")

or

def all_moneybooks(request):
    current_user = request.user

    if current_user.is_authenticated:
        current_user_moneybooks = current_user.owner.all

        start_date.strftime("%Y-%m-%d") for current_user_moneybook in current_user_moneybooks
        end_date.strftime("%Y-%m-%d") for current_user_moneybook in current_user_moneybooks

        return render(request, "home.html", context={"current_user": current_user, "all_moneybooks": all_moneybooks, "current_user_moneybooks": current_user_moneybooks})
    else:
        return render(request, "home.html", context={"current_user": current_user, "all_moneybooks": all_moneybooks})

and result :

start_date.strftime("%Y-%m-%d") for current_user_moneybook in current_user_moneybooks ^ SyntaxError: invalid syntax

dhooonk
  • 2,115
  • 3
  • 11
  • 17
  • What do you actually want to achieve? Do you want to change the format your model stores the date (this is not possible IMHO)? Do you want th change the way django displays the date in your template (you can use DATE_FORMAT in [settings](https://docs.djangoproject.com/en/dev/ref/settings/#date-format) or [template filters](https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date))? Do you want to generate a list of dates in a specific fomat for doing something else? – Chris Jan 18 '20 at 12:22
  • actually, my intend is how to control my datetime field which I show on the template. – dhooonk Jan 18 '20 at 14:04

1 Answers1

1

First of all, the syntax error you are getting is because of the wrong implementation of list comprehension.

Your iterator has to be within a list and also you need to use the iterator to modify it's attributes.

This

start_date.strftime("%Y-%m-%d") for current_user_moneybook in current_user_moneybooks

has to be like this

modified_dates = [current_user_moneybook.start_date.strftime("%Y-%m-%d") for current_user_moneybook in current_user_moneybooks]

"all_moneybooks" is the definition name and am not sure why you are sending that to the template.

If all you want to do is change the presentation of the date format in the template, you can do that using the django's builtin template filter like so

{{ some_date|date:’D, d M, Y' }} -> Thu, 03 Dec, 2015
Lag11
  • 542
  • 4
  • 9