python 如何在Django模板中调用函数?

x6yk4ghg  于 2022-11-27  发布在  Python
关注(0)|答案(2)|浏览(233)

我在我的www.example.com文件上有一个函数views.py,它连接到一个邮件服务器,然后将收件人的电子邮件地址附加到我的Django模型中。
在Django中,我用一个表来显示模型,我想包含一个按钮,叫做Get Email,并运行这个函数,然后它会用模型/表中的新数据重新加载页面。
这是我的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()

我的主urls.py

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

这是我在应用程序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'),
]

然后在我的subscribers.html上,我尝试了以下操作:

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

但我得到一个错误:

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

如何在模板中调用在www.example.com上定义的函数views.py?

gxwragnw

gxwragnw1#

Django默认不使用应用特定的urls.py文件,你必须在你的主urls.py中使用它们,例如:

from django.urls import include, path

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

假设您的应用程序名称为myapp

eeq64g8w

eeq64g8w2#

它应该是{% url 'getemails' %},因此:

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

**注意:**始终在每个路由的末尾给予/,因此URL应该类似于path('getemails/'...)

编辑:

看来你是在使用<form>标记,所以只需在action属性中定义为:

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

相关问题