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 viewsurlpatterns = [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' %}'" class="btn btn-primary">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?