Что я пробовал:
1.Настройки SMTP в settings.py:
Код: Выделить всё
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'myapppassword' # Gmail App Password
DEFAULT_FROM_EMAIL = '[email protected]'
На мой взгляд, я разрешаю продавцам отвечать на отзывы о продуктах. Когда поставщик отвечает, ответ сохраняется в модели ProductReview, и клиенту должно быть отправлено электронное письмо. Вот код представления:
Код: Выделить всё
@login_required
def product_reviews(request):
try:
vendor = Vendor.objects.get(user=request.user)
except Vendor.DoesNotExist:
return render(request, 'vendorpannel/no_vendor.html')
all_reviews = ProductReview.objects.filter(vendor=vendor)
if request.method == "POST":
review_id = request.POST.get('review_id')
reply_text = request.POST.get('reply_text')
if review_id and reply_text:
try:
review = ProductReview.objects.get(id=review_id, vendor=vendor)
review.reply = reply_text # Save the reply to the model
review.save()
# Send an email to the customer
customer_email = review.user.email
subject = "Reply to Your Product Review"
message = f"""
Dear {review.user.username},
The vendor has replied to your review for the product "{review.product.title}":
"{reply_text}"
Thank you for sharing your feedback.
Best regards,
Your Website Team
"""
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [customer_email])
return redirect('product_reviews') # Redirect to avoid form resubmission
except ProductReview.DoesNotExist:
# Handle invalid review_id
context = {
"all_reviews": all_reviews,
"error_message": "Review not found or you don't have permission to reply to this review.",
}
return render(request, "vendorpannel/product-reviews.html", context)
context = {
"all_reviews": all_reviews,
}
return render(request, "vendorpannel/product-reviews.html", context)
Вот часть HTML-шаблона, в которой поставщик может отправить ответ на обзор продукта:
Код: Выделить всё
{% for r in all_reviews %}
[img]{{r.product.image.url}}[/img]
Product Name: {{r.product.title}}
[b]Reviewer:[/b] Anon's Customer
[b]Rating:[/b] {{ r.rating }} Star{{ r.rating|pluralize }}
[b]Review:[/b] {{r.review}}
{% if review.reply %}
[b]Vendor Reply:[/b] {{ review.reply }}
{% else %}
{% csrf_token %}
Reply 2
{% endif %}
Your Reply:
Reply
{% endfor %}
Модель ProductReview используется для хранения отзывов и ответов, но поле ответа не обновляется правильно. Вот модель:
Код: Выделить всё
class ProductReview(models.Model):
user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True)
vendor=models.ForeignKey(Vendor, on_delete=models.SET_NULL,null=True,related_name="productreview")
product=models.ForeignKey(Product, on_delete=models.SET_NULL ,null=True,related_name="reviews")
review=models.TextField()
reply = models.TextField(null=True, blank=True)
rating = models.BigIntegerField(choices=RATING, default=3)
date=models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural="Product Reviews"
def __str__(self):
return self.product.title
def get_rating(self):
return self.rating
- Электронное письмо не отправляется:
Код: Выделить всё
socket.gaierror: [Errno 11001] getaddrinfo failed
- Модель не обновляется:
Что я пробовал:
- Дважды проверил настройки SMTP и убедился, что мой пароль приложения верен.
- Проверил, что для учетной записи Gmail настроена двухэтапная аутентификация и используется пароль приложения.
- Убедились, что поле ответа модели включено в форме и сохранено в представлении.
- Почему в этом случае не удается установить пароль приложения?
- Возникла ли проблема с настройкой электронной почты или проблемами сети на моем локальном компьютере?
- Почему поле ответа не обновляется в модели ProductReview, хотя я правильно сохраняю его в просмотреть?
- Что-то не так с моей моделью ProductReview или тем, как я сохраняю ответ?
Подробнее здесь: https://stackoverflow.com/questions/793 ... t-updating