I have an email submission form with 3 input fields:
#forms.py
class ContactForm(forms.Form):
name = forms.CharField(
widget=forms.TextInput(attrs={"placeholder": "* Your name"})
)
email = forms.EmailField(
widget=forms.TextInput(attrs={"placeholder": "* Your email address"})
)
message = forms.CharField(
widget=forms.Textarea(attrs={"placeholder": "* Your message"})
)
When a user submits the form, a flash message appears below the submit button confirming that the message has been sent.
#contact.html
<section id="form">
<form action="" method="post">
<h3>Send me an email</h3>
{% csrf_token %}
{{ form|crispy }}
<input type="submit" value="Send">
{% if messages %}
{% for message in messages %}
<div
class="text-center alert alert-{{ message.tags }}"
>
{{ message|safe }}
</div>
{% endfor %}
{% endif %}
</form>
</section>
#views.py
class ContactPageView(SuccessMessageMixin, FormView):
form_class = ContactForm
template_name = "contact.html"
success_url = reverse_lazy('contact') # Return back to the page containing the form
success_message = "Your message has been sent. Thankyou."
def form_valid(self, form):
email = form.cleaned_data.get("email")
name = form.cleaned_data.get("name")
message = form.cleaned_data.get("message")
# Displays in console
full_message = f"""
Email received from <{name}> at <{email}>,
________________________
{message}
"""
send_mail(
subject="Email from client using website form",
message=full_message,
from_email=settings.DEFAULT_FROM_EMAIL,
recipient_list=[settings.NOTIFY_EMAIL],
)
return super().form_valid(form)
The form works fine except that I would like the input values retained after the form has been submitted and with the flash message still displayed.
I’ve tried including a get_success_url function below the form_valid function hoping that the values would be displayed back in the form, but I get the following attribute error:
'ContactPageView' object has no attribute 'name'
.
#views.py
def get_success_url(self):
return reverse(
'contact',
kwargs={
'name': self.name,
'email': self.email,
'message': self.message,
},
)
I’m new to Django, so could someone point me in the right direction. Thanks.
Minsky is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.