Home > Net >  How to call a function in a Django template?
How to call a function in a Django template?

Time:11-27

I have a function on my views.py file that connects to a mail server and then appends to my Django model the email addresses of the recipients. The script works good.

In Django, I'm displaying the model with a table, and I'd like to include a button that says Get Emails and runs this function and it then reloads the page with the new data in the model / table.

This is my views.py:

class SubscriberListView(LoginRequiredMixin, SingleTableView):
model = EmailMarketing
table_class = EmailMarketingTable
template_name = 'marketing/subscribers.html'


# Get emails from email server
# Connection settings
HOST = 'xXxxxxXxXx'
USERNAME = 'xXxxxxXxXx'
PASSWORD = "xXxxxxXxXx"

m = imaplib.IMAP4_SSL(HOST, 993)
m.login(USERNAME, PASSWORD)
m.select('INBOX')

def get_emails():
    result, data = m.uid('search', None, "ALL")
    if result == 'OK':
        for num in data[0].split():
            result, data = m.uid('fetch', num, '(RFC822)')
            if result == 'OK':
                email_message_raw = email.message_from_bytes(data[0][1])
                email_from = str(make_header(decode_header(email_message_raw['From'])))
                email_addr = email_from.replace('<', '>').split('>')
                if len(email_addr) > 1:
                    new_entry = EmailMarketing(email_address=email_addr[1])
                    new_entry.save()
                else:
                    new_entry = EmailMarketing(email_address=email_addr[0])
                    new_entry.save()
            

# Close server connection
m.close()
m.logout()

My main urls.py:

urlpatterns = [
    path('marketing/', SubscriberListView.as_view(), name='marketing')
]

And this is what I tried on the app urls.py:

from django.urls import path
from django.contrib.auth import views as auth_views
from . import views

urlpatterns = [
    path('', views.marketing, name='marketing'),
    path('/getemails', views.get_emails, name='getemails'),
]

And then on my subscribers.html I tried this:

    <button type="submit" onclick="location.href='{% url 'getemails' %}'" >Get Emails</button>

But I get an error:

Reverse for 'getemails' not found. 'getemails' is not a valid view function or pattern name.

How can I call this function defined on my views.py inside my template?

CodePudding user response:

It should be {% url 'getemails' %} so:

  <button type="submit" onclick="location.href='{% url 'getemails' %}'" >Get Emails</button>

Note: Always give / at the end of every route so urls should be like path('getemails/'...).

Edit:

It seems that you are using <form> tag, so simply define in action attribute as:

<form method='POST' action="{% url 'getemails' %}">

CodePudding user response:

Django does not use app-specific urls.py files by default. You must include them in your main urls.py, for example:

from django.urls import include, path

urlpatterns = [
    path('marketing/', SubscriberListView.as_view(), name='marketing'),
    path('myapp/', include('myapp.urls')),
    ...
]

Assuming that your app name is myapp.

  • Related