Django emailmessage bug form

Hi I’m student and I have a problem with my contact form.

I try to add them to my website but my fields dot not appear.

views.py

from django.core.mail import EmailMessage
from . import forms

def contact(request):
    form = forms.ContactForm(request.POST)
    if request.method == 'POST':
        if form.is_valid():
            subject = form.cleaned_data['subject']
            from_email = form.cleaned_data['from_email']
            message = form.cleaned_data['message']
            email = EmailMessage(subject, message, from_email, ['mymail@gmail.com'])
            email.send()
            return redirect('success')
    else:
        return render(request, 'off/index.html', {'form': form})

forms.py

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)

        def __str__(self):
            return self.from_email

index.html

<form action="{% url 'index' %}" method="POST">
  {% csrf_token %}
  {% for field in form %}
      {{ field.label_tag }}
      {{ field }}
      {% for error in field.errors %}
        <p style="color: red">{{ error }}</p>
      {% endfor %}
  {% endfor %}
  <input type="submit" value="Submit"/>
</form>

It looks like the the template is not being passed a blank form when the contact() view is called. Try editing the view like so:

from django.core.mail import EmailMessage
from . import forms

def contact(request):
   form = forms.ContactForm(request.POST)
   if request.method == 'POST':
       if form.is_valid():
           subject = form.cleaned_data['subject']
           from_email = form.cleaned_data['from_email']
           message = form.cleaned_data['message']
           email = EmailMessage(subject, message, from_email, ['mymail@gmail.com'])
           email.send()
           return redirect('success')
   else:
       form = forms.ContactForm()
       return render(request, 'off/index.html', {'form': form})

Hope this helps!

When you are running it and requesting your view, do you get any text showing up in the console where you’ve issued your runserver command? It’s possible that there’s an error there that’s not directly related to the code being displayed here.