PacktPublishing / Django-4-by-example

Django 4 by example (4th Edition) published by Packt
https://djangobyexample.com/
MIT License
818 stars 461 forks source link

Shop e-mail invoices #24

Closed PRCervera closed 1 year ago

PRCervera commented 1 year ago

Hi,

I cannot print the translated invoice that is sent by email in the payment process.

It always comes out with the source language.

Template process.html is fully adapted.

Does anyone else have this problem?

Maybe Celery needs some parameters about the language active... I don't know.

I would appreciate some help,

Thank you.

PRCervera commented 1 year ago

Sorry,

Template name is pdf.html.

Regards

zenx commented 1 year ago

@PRCervera can you attach your views.py and pdf.html files?

PRCervera commented 1 year ago

Thank you !

orders.zip payments.zip

zenx commented 1 year ago

Sorry @PRCervera, I didn't understand your issue correctly previously.

Celery workers are not aware of the current language. Django determines the current language using the LocaleMiddleware. As celery tasks are processed out of any request scope, they fall back to the base language defined with the LANGUAGE_CODE setting. You can do the following to use the request language for the email sent with Celery:

In the order_create view in order/views.py add request.LANGUAGE_CODE as follows:

order_created.delay(order.id, request.LANGUAGE_CODE)

And then in order/tasks.py you can activate the given language before sending the email:

from django.utils.translation import activate
# ...

@shared_task
def order_created(order_id, language_code):
    activate(language_code)
    # ...

This is a good improvement to add to the book examples. Thank you.

PRCervera commented 1 year ago

Now it works !

Thanks to you !!!