Контактная форма Django и bootstrap не работает

Я пытаюсь сделать контактную форму Django со стилями bootstrap, но она не работает. Я пробовал в представлениях использовать send_mail вместо EmailMessage, но все равно не работает. Когда я нажимаю на кнопку "Отправить", страница просто перезагружается и больше ничего не происходит, я не получаю никакого письма. Обратите внимание, что я изменил адрес электронной почты и пароль в целях безопасности, но это учетная запись gmail. Вот мои файлы:

home.html

<footer class="bg-dark text-white pt-3" id="contact">
    <div class="row text-center col-lg-12"> 
      <div>
        <h3>Contact</h3>
        <img src="{% static 'home_app/img/contact.png' %}" class="img-fluid">
      </div>
    </div>

    <div class="col-lg-12 mx-auto">
      <form method="post">
        {% csrf_token %}
        <div class="row">
          <div class="col-lg-6 col-sm-3" >
            <input type="text" class="form-control" name="name" placeholder="Name and last name" required>
          </div>
          <div class="col-lg-6 col-sm-3">
            <input type="tel" class="form-control" name="subject" placeholder="Subject" required>
          </div>
          <div class="col-lg-12 col-sm-6">
            <input type="text" class="form-control" name="email" placeholder="email@example.com" required>
          </div>
          <div class="col-lg-12 col-sm-6">
            <textarea class="form-control" name="text" placeholder="Write your message" rows="5"></textarea>  
          </div>
          <div class="col-lg-12">
            <button type="Submit" class="btn btn-primary w-100 fs-5">Send</button>
          </div>
        </div>
      </form>
    </div>
  </footer>

views.py

from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.core.mail import EmailMessage
    
    def contact(request):
        if request.method == "POST":
            name = request.POST.get('name')
            subject = request.POST.get('subject')
            email = request.POST.get('email')
            message = request.POST.get('text')
            return redirect('contact')
       
            email=EmailMessage("Message from Django",
            "User: {} Subject: {} Address: {} Message:\n\n {}".format(name,subject,email,message),
            "",["email@example.com"],reply_to=[email])
        
            try: 
                email.send()
                return redirect("/?valid")
        
            except:
                return redirect("/?notvalid")   
        
            return render(request,'home_app/home.html',{})

setting.py

EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.gmail.com"
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False
EMAIL_PORT = 587
EMAIL_HOST_USER = "email@example.com"
EMAIL_HOST_PASSWORD = "password123"

Если кто-то может мне помочь, я буду очень благодарен

return render(request,'home_app/home.html',{}) не возвращает никаких контекстов.

Вы можете рассмотреть одну из функций моего проекта

def list_auction(request, id):
    lists = AuctionList.objects.filter(id = id).first()
    bid = AuctionBid.objects.filter(lists = lists)
    comment = AuctionComment.objects.filter(lists = lists)
    highest_bid = lists.starting_bid
    if bid is not None:
        for bids in bid:
            if bids.input_value > highest_bid:
                highest_bid = bids.input_value
    if request.method == 'POST':
        user = request.user
        lists = AuctionList.objects.filter(id = id).first()
        comment = request.POST.get('comment', None)
        input_value = request.POST.get('Auction_price', None)
        try:
            input_value = float(input_value)
        except:
            input_value = None
        if comment is not None:
            comm = AuctionComment.objects.create(comment = comment, user = user, lists = lists)
            comm.save()
            return HttpResponseRedirect(reverse('lists', args = [id]))
        if input_value is not None:
            if float(input_value) < highest_bid:
                return HttpResponseRedirect(reverse('lists', args = [id]))
            bid = AuctionBid.objects.create(input_value = float(input_value), user = user, lists =lists)
            bid.save()
            prev_bid = AuctionBid.objects.filter(lists = lists).exclude(input_value = input_value)
            prev_bid.delete()
            return HttpResponseRedirect(reverse('lists', args = [id]))
        if comment is None and input_value is None:
            return render(request, "auctions/error.html", {"message": "Please bid the product or add a comment."})
    context = {"lists": lists, "highest_bid":highest_bid, "min_bid":(highest_bid + 0.50),"comment":comment}
    return render(request, "auctions/lists.html", {"context"=context}  )
        

Смотрите последнюю строку кода.

Вы можете видеть, что при рендеринге я возвращаю в HTML что-то, что я хочу увидеть в данном конкретном Html-файле. Вам нужно добавить что-то вроде контекста, чтобы увидеть результат, или вы можете управлять задачей с помощью JavaScript. В этом случае вам не нужно возвращать context.

Я решил проблему. У home.html есть свой собственный вид под названием home, и раздел контактов находится в этом html, поэтому по какой-либо причине вид контактов не мог отвечать, пока раздел контактов html находился в виде дома. Решением было создание html для раздела контактов, только с этим вид контактов мог отвечать

Вернуться на верх