1

django-recaptcha我正在尝试使用该应用程序在客户网站上设置联系表,并且django-crispy-forms. 我的表单数据没有通过is_valid()POST 传递,我无法弄清楚。任何帮助将不胜感激!(使用 Python 3.8.5 在 Windows 10 上运行 Django 3.11。)据我所知,我已经根据规范设置了所有配置。

这是models.py

from django.db import models

class ContactEmail(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    first_name = models.CharField(blank=False, max_length=50)
    last_name = models.CharField(blank=False, max_length=50)
    email = models.EmailField(blank=False)
    phone = models.CharField(max_length=32, blank=True)
    subject = models.CharField(blank=False, max_length=80)
    message = models.TextField(blank=False)

    def __str__(self):
        return "{} {}: {} ({})".format(
            self.first_name,
            self.last_name,
            self.subject,
            self.created.strftime("%m/%d/%Y, %H:%M:%S UTC")
        )

表格.py

from django import forms
from django.urls import reverse

from .models import ContactEmail

from captcha.fields import ReCaptchaField
from captcha.widgets import ReCaptchaV3
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit


class ContactForm(forms.ModelForm):

    captcha = ReCaptchaField(widget=ReCaptchaV3(attrs={
        'data-theme': 'dark',
        'data-size': 'compact'
    }))

    class Meta:
        model = ContactEmail
        fields = [
            'first_name',
            'last_name',
            'email',
            'phone',
            'subject',
            'message',
        ]

    def __init__(self, *args, **kwargs):
        super(ContactForm, self).__init__(*args, **kwargs)
        self.fields['captcha'].label = False
        self.helper = FormHelper()
        self.helper.add_input(Submit('submit', 'Submit', css_class='btn-block'))
        self.helper.form_method = 'POST'
        self.helper.form_action = reverse('contact')

视图.py

import datetime

from django.contrib import messages
from django.core.mail import send_mail
from django.http import HttpResponse
from django.shortcuts import redirect, render
from django.template.loader import render_to_string
from django.urls import resolve
from django.utils.html import strip_tags

from .forms import ContactForm
from .models import ContactEmail

def add_now():
    now = datetime.datetime.now()
    return now

# ...

def contact(request):
    context = {
        'form': ContactForm(),
    }
    context['now'] = add_now()

    if request.method == 'GET':
        return render(
            request,
            template_name='website/contact.html',
            context=context
        )
    elif request.method == 'POST':
        form = ContactForm(request.POST)

        if form.is_valid():
            first_name = form.cleaned_data.get('first_name')
            last_name = form.cleaned_data.get('last_name')
            email = form.cleaned_data.get('email')
            phone = form.cleaned_data.get('phone')
            subject = form.cleaned_data.get('subject')
            message = form.cleaned_data.get('message')

            html_message = render_to_string(template_name='website/email.html', context={
                'first_name': first_name,
                'last_name': last_name,
                'email': email,
                'phone': phone,
                'subject': subject,
                'message': message,
            })
            plain_message = strip_tags(html_message)

            recipients = ['*** (my email address, for testing)',]

            try:
                send_mail(
                    subject,
                    plain_message,
                    '*** (client email address)',
                    recipients,
                    html_message=html_message
                )
                contact_email = ContactEmail(
                    first_name=first_name,
                    last_name=last_name,
                    email=email,
                    phone=phone,
                    subject=subject,
                    message=message
                )
                contact_email.save()
                print("Message was sent and saved.")
                messages.add_message(request, messages.SUCCESS, 'Your email was sent.')
            except Exception as e:
                messages.add_message(request, messages.ERROR, 'Your email was not sent: {}'.format(e))
            finally:
                return redirect('contact')

        else:
            return redirect('contact')

联系人.html

{% extends 'website/base.html' %}

{% load static %}
{% load crispy_forms_tags %}

{% block description %}{% endblock %}
{% block title %}Contact{% endblock %}

{% block content %}
<div class="col-md-6 offset-md-3 mb-5">
    {% crispy form form.helper %}
</div>
{% endblock %}

电子邮件.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        Name: {{ first_name }} {{ last_name }}<br>
        Email: {{ email }}<br>
        {% if phone %}Phone: {{ phone }}<br>{% endif %}
        Subject: {{ subject }}<br><br>
        Message:<br>
        {{ message }}<br>
    </body>
</html>

还有我的requirements.txt

asgiref==3.2.10
astroid==2.4.2
beautifulsoup4==4.9.1
colorama==0.4.3
dj-database-url==0.5.0
Django==3.1.1
django-bootstrap4==2.2.0
django-crispy-forms==1.9.2
django-recaptcha==2.0.6
gunicorn==20.0.4
isort==5.5.3
lazy-object-proxy==1.4.3
mccabe==0.6.1
psycopg2==2.8.6
pylint==2.6.0
pytz==2020.1
six==1.15.0
soupsieve==2.0.1
sqlparse==0.3.1
toml==0.10.1
whitenoise==5.2.0
wrapt==1.12.1
4

0 回答 0