How to call a function in a Django template?

2024/10/5 19:49:12

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?

Answer

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, pathurlpatterns = [path('marketing/', SubscriberListView.as_view(), name='marketing'),path('myapp/', include('myapp.urls')),...
]

Assuming that your app name is myapp.

https://en.xdnf.cn/q/119634.html

Related Q&A

Remove duplicates from json file matching against multiple keys

Original Post = Remove duplicates from json dataThis is only my second post. I didnt have enough points to comment my question on the original post...So here I am.Andy Hayden makes a great point - &quo…

Merging CSVs with similar name python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 8…

urllib.error.HTTPError: HTTP Error 403: Forbidden

I get the error "urllib.error.HTTPError: HTTP Error 403: Forbidden" when scraping certain pages, and understand that adding something like hdr = {"User-Agent: Mozilla/5.0"} to the h…

Compare multiple file name with the prefix of name in same directory

I have multiple .png and .json file in same directory . And I want to check where the files available in the directory are of same name or not like a.png & a.json, b.png & b.json

how to make a unique data from strings

I have a data like this . the strings are separated by comma."India1,India2,myIndia " "Where,Here,Here " "Here,Where,India,uyete" "AFD,TTT"What I am trying…

How to read complex data from TB size binary file, fast and keep the most accuracy?

Use Python 3.9.2 read the beginning of TB size binary file (piece of it) as below: file=open(filename,rb) bytes=file.read(8) print(bytes) b\x14\x00\x80?\xb5\x0c\xf81I tried np.fromfile np.fromfile(np…

How to get spans text without inner attributes text with selenium?

<span class="cname"><em class="multiple">2017</em> Ford </span> <span class="cname">Toyota </span>I want to get only "FORD" …

List of 2D arrays with different size into 3D array [duplicate]

This question already has answers here:How do you create a (sometimes) ragged array of arrays in Numpy?(2 answers)Closed last year.I have a program that generating 2D arrays with different number of r…

How can I read data from database and show it in a PyQt table

I am trying to load data from database that I added to the database through this code PyQt integration with Sqlalchemy .I want the data from the database to be displayed into a table.I have tried this …

Python: Cubic Spline Regression for a time series data

I have the data as shown below. I want to find a CUBIC SPLINE curve that fits the entire data set (link to sample data). Things Ive tried so far:Ive gone through scipys Cubic Spline Functions, but all …