我正在与Django建立EC市场。 我们创建了商店列表页面和商店详情页面。此外,我希望能够在商店的详细信息页面上向每个商店发送邮件。
但是,我们不知道如何在商店详情页面上发送邮件时将send_mail的recipient_list更改为每个商店的mailAddress。
■view.py
import collections
with open("common.txt", "r") as f: # open the `common.txt` for reading
common_words = {l.strip().lower() for l in f} # read each line and and add it to a set
interpunction = ";,'\"." # define word separating characters and create a translation table
trans_table = str.maketrans(interpunction, " " * len(interpunction))
sentences_counter = [] # a list to hold a word count for each sentence
word_counter = collections.defaultdict(int) # a string:int default dict for counting
with open("sample.txt", "r") as f: # open the `sample.txt` for reading
for line in f: # read the file line by line
for word in line.translate(trans_table).split(): # remove interpunction and split
if word.lower() not in common_words: # count only words not in the common.txt
word_counter[word.lower()] += 1 # increase the count
print("\n".join("{}: {}".format(w, c) for w, c in word_counter.items())) # print the counts
■model.py
from django.views import generic
from django.views.generic.edit import ShopView
from django.views.generic.edit import FormMixin
from .models import Shop
from .forms import ContactForm
class ShopView(FormMixin, generic.DetailView):
model = Shop
form_class = ContactForm
def get_template_names(self):
return 'shopSearch/shop_detail.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context
def get_success_url(self):
return 'contact/finish/'
def post(self, request, *args, **kwargs):
self.object = self.get_object()
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self, form):
form.send_email()
return super().form_valid(form)
■form.py
class Shop(models.Model):
name = models.CharField(max_length=255)
mailAddress = models.CharField(max_length=100, null=True, blank=True)
答案 0 :(得分:0)
您可以将send_email与to
一起使用。
class ContactForm(forms.Form):
title = forms.CharField()
email = forms.EmailField()
contents = forms.CharField(widget=forms.Textarea)
def send_email(self, to):
subject = self.cleaned_data['title']
from_email = self.cleaned_data['email']
contents = self.cleaned_data['contents']
message = '\n\ncontens:\n' + contents + '\n\nfrom to:\n' + from_email
send_mail(subject, message, settings.EMAIL_HOST_USER, to)
并在to
中传递form_valid()
列表。
...
def form_valid(self, form):
# set to email list for your model
# maybe you want to this?
to = [self.object.mailAddress]
form.send_email(to)
return super().form_valid(form)