#django #django-views #bootstrap-5 #django-settings
Вопрос:
Я пытаюсь создать контактную форму Django со стилями начальной загрузки, но это не работает. Я пробовал в представлениях с 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:nn {}".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"
Если кто-нибудь может мне помочь, я буду очень благодарен
Ответ №1:
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. В этом случае вам не нужно возвращать контекст.
Ответ №2:
Я решил эту проблему. в home.html имеет собственное представление «Главная страница», и раздел «контакты» находится в этом html-файле, поэтому по какой-либо причине представление «контакты» не могло ответить, пока раздел html «контакты» находился в домашнем представлении. Решением было создание html-кода для раздела контактов, только с помощью которого представление контактов могло отвечать