Home > Net >  Where the right place to put recurrent function in Django
Where the right place to put recurrent function in Django

Time:12-27

I want to make a function that will be used in different parts of my application. It is a function to send email notifications, something like:

def mail_notification():
    subject = 'New Product' 
    from_email = '[email protected]'
    to = '[email protected]'
    html_content = render_to_string('email/new_message_product_client_email.html')
    msg = EmailMultiAlternatives(subject, html_content, from_email, [to])
    msg.content_subtype = "html"
    msg.send()

My doubt is, in a View, signals.py, forms.py, Django have a "right" place or is where i prefer?

CodePudding user response:

I recommend create separate place to store common functions. Here my default project structure for Django

django-app/
    django-app/
        users/  # django application
            migrations/
            models.py
            views.py
            tests.py
            utils.py # Here I place helper functions related to User application
        common/  # folder with common functions for all django applications
            email.py # functions to work with email
            string.py # hepler functions to parse and modify strings 
            ...

So, I recommend to place your function in common/email.py and import it in models and views.

  • Related