首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django联系人电子邮件表单不会在模板home.html中呈现/显示。

问Django联系人电子邮件表单不会在模板home.html中呈现/显示。
EN

Stack Overflow用户
提问于 2021-01-19 12:23:43
回答 2查看 109关注 0票数 1

Django项目结构

父目录: personal_portfolio_project主子目录(包含设置):personal_portfolio应用程序: portfolio,blog

包含所有应用程序的整个项目的目录结构(通过树打印在控制台中):

代码语言:javascript
复制
├── personal_portfolio_project
│   ├── blog
│   │   ├── __init__.py
│   │   ├── __pycache__
│   │   │   ├── __init__.cpython-39.pyc
│   │   │   ├── admin.cpython-39.pyc
│   │   │   ├── models.cpython-39.pyc
│   │   │   ├── urls.cpython-39.pyc
│   │   │   └── views.cpython-39.pyc
│   │   ├── admin.py
│   │   ├── apps.py
│   │   ├── migrations
│   │   │   ├── 0001_initial.py
│   │   │   ├── 0002_auto_20210117_1306.py
│   │   │   ├── 0003_auto_20210117_1309.py
│   │   │   ├── 0004_auto_20210117_1432.py
│   │   │   ├── __init__.py
│   │   │   └── __pycache__
│   │   │       ├── 0001_initial.cpython-39.pyc
│   │   │       ├── 0002_auto_20210117_1306.cpython-39.pyc
│   │   │       ├── 0003_auto_20210117_1309.cpython-39.pyc
│   │   │       ├── 0004_auto_20210117_1432.cpython-39.pyc
│   │   │       └── __init__.cpython-39.pyc
│   │   ├── models.py
│   │   ├── templates
│   │   │   └── blog
│   │   │       ├── all_blogs.html
│   │   │       └── detail.html
│   │   ├── tests.py
│   │   ├── urls.py
│   │   └── views.py
│   ├── db.sqlite3
│   ├── manage.py
│   ├── media
│   │   └── portfolio
│   │       └── images
│   │           ├── DSC_0004a.jpg
│   │           └── DSC_0010a.jpg
│   ├── personal_portfolio
│   │   ├── __init__.py
│   │   ├── __pycache__
│   │   │   ├── __init__.cpython-39.pyc
│   │   │   ├── settings.cpython-39.pyc
│   │   │   ├── urls.cpython-39.pyc
│   │   │   └── wsgi.cpython-39.pyc
│   │   ├── asgi.py
│   │   ├── settings.py
│   │   ├── urls.py
│   │   └── wsgi.py
│   ├── portfolio
│   │   ├── __init__.py
│   │   ├── __pycache__
│   │   │   ├── __init__.cpython-39.pyc
│   │   │   ├── admin.cpython-39.pyc
│   │   │   ├── forms.cpython-39.pyc
│   │   │   ├── models.cpython-39.pyc
│   │   │   └── views.cpython-39.pyc
│   │   ├── admin.py
│   │   ├── apps.py
│   │   ├── forms.py
│   │   ├── migrations
│   │   │   ├── 0001_initial.py
│   │   │   ├── __init__.py
│   │   │   └── __pycache__
│   │   │       ├── 0001_initial.cpython-39.pyc
│   │   │       └── __init__.cpython-39.pyc
│   │   ├── models.py
│   │   ├── static
│   │   │   └── portfolio
│   │   │       ├── CV_Andreas_Luckert.pdf
│   │   │       ├── DSC_0010a.jpg
│   │   │       ├── Logo_Andreas_Luckert.png
│   │   │       ├── Logo_ZappyCode_DjangoCourse.png
│   │   │       ├── custom.css
│   │   │       └── main.js
│   │   ├── templates
│   │   │   └── portfolio
│   │   │       ├── about.html
│   │   │       ├── base.html
│   │   │       └── home.html
│   │   ├── tests.py
│   │   └── views.py
│   └── test_sendgrid.py

故事-线

我在"portfolio“应用程序中有一个portfolio/forms.py文件,其内容如下:

代码语言:javascript
复制
from django import forms

class ContactForm(forms.Form):
    from_email = forms.EmailField(required=True)
    subject = forms.CharField(required=True)
    message = forms.CharField(widget=forms.Textarea, required=True)
    # From docs: https://docs.djangoproject.com/en/3.1/topics/forms/#more-on-fields
    cc_myself = forms.BooleanField(required=False)

在portfolio/views.py中,我有以下相关部分:

代码语言:javascript
复制
from .forms import ContactForm  # import module from same parent folder as this script
import General.Misc.general_tools as tools  # custom module to import special-print function

def contactView(request, admin_email='blaa@blaaa.com'):

    if request.method == 'GET':
        sendemail_form = ContactForm()
    else:
        sendemail_form = ContactForm(request.POST)

        if sendemail_form.is_valid():
            # * Retrieve data and set up e-mail (subject, sender, message)
            subject = sendemail_form.cleaned_data['subject']
            from_email = sendemail_form.cleaned_data['from_email']
            message = sendemail_form.cleaned_data['message']
            # From docs: https://docs.djangoproject.com/en/3.1/topics/forms/#more-on-fields
            cc_myself = sendemail_form.cleaned_data['cc_myself']

            recipients = [admin_email]
            if cc_myself:
                recipients.append(from_email)

            # * Send email
            try:
                # General Django docs: https://docs.djangoproject.com/en/3.1/topics/email/#send-mail
                # NOTE on passed list as 4th parameter: recipient-list

                ## i) How to set up an email contact form - docs: https://learndjango.com/tutorials/django-email-contact-form
                send_mail(subject,
                          message,
                          from_email,
                          recipients,
                          fail_silently=False)

            # * Exceptions * #
            # NOTE on scope: security
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            # General exception to be printed out
            except Exception as e:
                tools.except_print(f"ERROR:\n{e}")

            # Return success (if this code is reached)
            return redirect('success')

    # Send the completed (filled-in) form to the homepage - HTML - document
    return render(request, "portfolio/home.html",
                  {'sendemail_form': sendemail_form})


def successView(request):
    return HttpResponse('Success! Thank you for your message.')

这是我在portfolio/templates/portfolio/home.html末尾包含的联系人表单( HTML的其余部分工作非常好,通常Django在显示localhost-webpage时不会在控制台中显示任何错误):

代码语言:javascript
复制
<!-- ** E-Mail contact form **
Docs: https://learndjango.com/tutorials/django-email-contact-form-->

{% if sendemail_form %}
    <h2 class="mt-5">Contact Me</h2>
    <hr>
    <form method="post">
        {% csrf_token %}
        <!-- NOTE on ".as_p": https://docs.djangoproject.com/en/3.1/topics/forms/#form-rendering-options
        Possible attributes: as_table, as_p, as_ul -->
        {{ sendemail_form.as_p }}
        <div class="form-actions">
            <button type="submit">Send</button>
        </div>
    </form>
{% endif %}

我的personal_portfolio/urls.py的内容如下:

代码语言:javascript
复制
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings  # get info from the settings.py - file
from portfolio import views  # other views could also be imported (e.g. from the blog-app)

urlpatterns = [
    path("", views.home, name="home"),

    # Docs: https://learndjango.com/tutorials/django-email-contact-form
    path("contact/", views.contactView, name='contact'),
    path("success/", views.successView, name='success'),

    # Add "About me" for additonal info about the creator of the webpage
    path("about/", views.about, name="about"),

    # Standard admin page
    path('admin/', admin.site.urls),

    # NOTE on include: forwarding all /blog/ - related requests to the blog-app
    path('blog/', include('blog.urls')),
]

# * Add a static link to the MEDIA - files * #
# NOTE on processing: import certain variables defined in the settings.py of this project
# Docs: google django images (or media (folder)) etc.
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

我尝试在portfolio/admin.py中注册表单,就像在portfolio/models.py中定义的类一样,但首先我不知道这是否必要,其次,由于TypeError: 'DeclarativeFieldsMetaclass' object is not iterable,它甚至没有工作,所以我后来从portfolio/admin.py中删除了以下代码:

代码语言:javascript
复制
from django.contrib import admin
# !!! CAUTON: TypeError: 'DeclarativeFieldsMetaclass' object is not iterable
from .forms import ContactForm

# NOTE on registering form: doesn't work due to the following error:
# TypeError: 'DeclarativeFieldsMetaclass' object is not iterable
admin.site.register(ContactForm)

总的来说,我对如何使表单最终出现在我的portfolio/templates/portfolio/home.html上感到困惑。当{% if sendemail_form %}扫描要传递的non-None表单时,这表明表单没有按应有的方式正确传递。

Test以检查调用联系人表单的views.py中的函数contactView()是否达到了其中的打印输出:

代码语言:javascript
复制
$ python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
January 19, 2021 - 14:16:37
Django version 3.1.5, using settings 'personal_portfolio.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[19/Jan/2021 14:16:42] "GET / HTTP/1.1" 200 31617
[19/Jan/2021 14:16:42] "GET /static/portfolio/custom.css HTTP/1.1" 304 0
[19/Jan/2021 14:16:42] "GET /static/portfolio/main.js HTTP/1.1" 304 0
[19/Jan/2021 14:16:43] "GET /static/portfolio/Logo_ZappyCode_DjangoCourse.png HTTP/1.1" 200 442438
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-01-19 14:46:51

您需要在主视图中创建呈现主页的ContactForm。我们需要这样做,因为表单出现在主页模板中;如果我们不在此视图中添加表单,则模板的联系人表单部分永远不会工作,因为它接收到了None。

代码语言:javascript
复制
def home(request):
    ... your code here ...

    # send empty contact form to template
    sendemail_form = ContactForm()

    return render(
        request,
        "portfolio/home.html",
        {'sendemail_form': sendemail_form})

那么contactView不应该呈现模板,只需重定向即可。contactView的工作是获取POST数据并对其进行处理,并将其重定向到不同的视图;它不应该呈现模板。

代码语言:javascript
复制
def contactView(request, admin_email='blaa@blaaa.com'):
    if request.method == 'POST':
        sendemail_form = ContactForm(request.POST)

        if sendemail_form.is_valid():
            subject = sendemail_form.cleaned_data['subject']
            from_email = sendemail_form.cleaned_data['from_email']
            message = sendemail_form.cleaned_data['message']
            cc_myself = sendemail_form.cleaned_data['cc_myself']

            recipients = [admin_email]
            if cc_myself:
                recipients.append(from_email)

            try:
                send_mail(subject,
                          message,
                          from_email,
                          recipients,
                          fail_silently=False)
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            except Exception as e:
                tools.except_print(f"ERROR:\n{e}")
                return HttpResponse('errors.')

            # Return success (if this code is reached)
            return redirect('success')

    # return to home page
    return redirect('home')

另外,将联系人表单(位于主页模板中)指向正确的URL (这是联系人URL,而不是主页URL);您可以更改:

代码语言:javascript
复制
{% if sendemail_form %}
    ...
    <form method="post">
    ...
{% endif %}

至

代码语言:javascript
复制
{% if sendemail_form %}
    ...
    <form method="post" action="{% url 'contact' %}">
    ...
{% endif %}
票数 2
EN

Stack Overflow用户

发布于 2021-01-19 13:38:05

我认为您需要向联系人HTML表单添加正确的URL。

您说HTML位于主页中,但HTML没有指定不同的action (目标views.home),因此它将向主页views.home发送(发送HTTP请求),后者使用视图views.home,这不是您所需要的。

通过在表单中指定不同的HTML属性,页面将将数据发送到不同的contact(应该是views.contactView ),然后使用视图views.contactView。

尝试更改联系人表单的HTML代码(在主页模板中)

代码语言:javascript
复制
{% if sendemail_form %}
    ...
    <form method="post">
    ...
{% endif %}

至

代码语言:javascript
复制
{% if sendemail_form %}
    ...
    <form method="post" action="{% url 'contact' %}">
    ...
{% endif %}

另外,还可以在主页的视图中添加ContactForm()。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65791444

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档