E
E
Eugene2016-04-06 00:29:20
Django
Eugene, 2016-04-06 00:29:20

How to fix the problem with the incessant sending of letters through the form on the site?

Good evening.
There is a site where the application form is on all pages. To simplify the work, I created a context processor for forms.py. The letter form submits, but an infinite number, i.e. the sending process does not end until you stop it forcibly.
forms.py

from django.core.context_processors import request
from django import forms
from django.shortcuts import render
from django.http import HttpResponse
from django.core.mail import send_mail, BadHeaderError
class ContactForm(forms.Form):
  subject = forms.CharField(max_length=100,widget=forms.TextInput(attrs = {'required': 'required'}))
  sender = forms.EmailField(widget=forms.TextInput(attrs = {'required': 'required'}))
  message = forms.CharField(widget = forms.Textarea(attrs = {'required': 'required'}))
  copy = forms.BooleanField(required = False)
def my_form(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            subject = form.cleaned_data['subject']
            sender = form.cleaned_data['sender']
            message = form.cleaned_data['message']
            copy = form.cleaned_data['copy']
            plus = message + ' ' + sender

            recipients = ['[email protected]']
            if copy:
                recipients.append(sender)
            try:
                send_mail(subject, plus, '[email protected]', recipients)
            except BadHeaderError: 
                return HttpResponse('Invalid header found')
            return render(request, 'single_index.html')
    else:
        form = ContactForm()
    return {'form': form}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mr_Floppy, 2016-04-06
@Mr_Floppy

Upon successful processing of the form, you need to do not render, but redirect (because when you press F5, the form will be sent again)
On the last line, you return the form, but you need to render(request, 'single_index.html', {'form': form} )
request does not need to be imported at all, it is an argument to the view function.
It is also not clear why wrap send_mail in try...except and catch only BadHeaderError. I would catch a wider class of errors and tell the user that the submission failed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question