简体   繁体   中英

Forbidden (CSRF token missing or incorrect.): Django form

I'm trying to subscribe an email account into a newsletter using Django, when I try to click the Go button I get the error Forbidden (CSRF token missing or incorrect.):

Here is the views.py method:

def newsletterSubscribe(request):
try:
    form = NewsletterUserSignUpForm(request.POST or None)

    if form.is_valid():
        instance = form.save(commit=False)
        if NewsletterUser.objects.filter(email=instance.email).exists():
            messages.warning(request, _('Alerta! El correo ingresado ya se encuentra suscrito.'),
                             'alert alert-warning alert-dismissible')
        else:
            instance.save()
            messages.success(request, _('Correo agregado con exito!'),
                             'alert alert-success alert-dismissible')

            subject = _('Gracias por unirse a nuestro boletín')
            message = _("""Bienvenido al boletín de ADA Robotics. Si deseas no estar suscrito visita: 
                        https://127.0.0.1:8000/unsubscribed""")
            msg = MIMEMultipart('alternative')
            msg['From'] = settings.EMAIL_HOST_USER
            msg['To'] = instance.email
            msg['Subject'] = subject
            part = MIMEText(message, 'plain')
            msg.attach(part)

            mail = smtplib.SMTP(settings.EMAIL_HOST, settings.EMAIL_PORT, timeout=20)
            mail.starttls()

            """
                template = get_template("myapp/sample_template.html")
                context = Context(context_data)
                body_html = template.render(context_data)
                body_text = strip_tags(body_html)
                part1 = MIMEText(body_text, 'plain')
                part2 = MIMEText(body_html, 'html')
                msg.attach(part1)
                msg.attach(part2)
            """

            emailto = [instance.email]
            mail.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD)
            mail.sendmail(settings.EMAIL_HOST_USER, emailto, msg.as_string())
            mail.quit()

            """from_email = settings.EMAIL_HOST_USER
                to_email = [instance.email]

                send_mail(subject=subject, from_email=from_email, recipient_list=to_email, message=message, fail_silently=False)"""

    context = {
        'form': form,
    }
    template = 'subscribed.html'
    #return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
    return render(request, template, context)
except Exception as ex:
    return render(request, '404.html')

Here is the template code:

<form id="newsletterForm" action="{% url "newsletterSubscribe" %}" method="POST" class="mr-4 mb-3 mb-md-0">
                            {% csrf_token %}
                            <div class="input-group input-group-rounded">
                                <input class="form-control form-control-sm bg-light" placeholder="Email Address" name="email" id="newsletterEmail" type="text">
                                <span class="input-group-append">
                                    <button class="btn btn-light text-color-dark" type="submit"><strong>GO!</strong></button>
                                </span>
                            </div>
                        </form>

Here is my urls.py:

path('contact/', contact, name="contact"),
path('subscribed/', newsletterSubscribe, name="newsletterSubscribe"),

I have the middleware added into my settings file and also migrate the database to have the tables already created.

What I'm trying to do is a form for a newsletter and is located in the base.html of the templates so it can be available in all the other pages around the web app.

You need to pass the context which includes the form object into the render function. You're form is loading because it's all html, but the {% csrf_token %} isn't loading because you haven't passed the form object into the template.

https://docs.djangoproject.com/en/3.0/topics/http/shortcuts/#render

render(request, template_name, context=None, content_type=None, status=None, using=None)

yours would be:

return render(request, template, context)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM