这里我有一个新闻通讯代码,如果要从新闻通讯表单中添加新电子邮件,我想发出通知,例如在管理员页面的模型名称内添加1条新电子邮件。然后不应该在模型名称中添加新邮件之类的消息。我该怎么办?有人可以帮我编辑此代码吗?
异常类型:TypeError
异常值:
Newsletter类型的对象不可JSON序列化
models.py
class Newsletter(models.Model):
email = models.EmailField()
date_joined = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.email
forms.py
class NewsletterForm(forms.ModelForm):
# def clean_email(self):
# email = self.cleaned_data['email']
# if User.objects.filter(email=email).exists():
# raise ValidationError('You Already Joined')
# return email
class Meta:
model = Newsletter
fields = '__all__'
views.py
def newsletter(request):
initial = {'email': [], 'count': 0}
session = request.session.get('data', initial)
if request.method == "POST":
form = NewsletterForm(request.POST or None)
if form.is_valid():
email = form.save(commit=False)
session['email'].append(email)
session['count'] += 1
request.session['data'] = session
email.save()
messages.success(request, 'Thank You for Joining.')
return redirect('/')
index.html
{% for model in app.models %}
<tr class="model-{{ model.object_name|lower }}">
{% if model.admin_url %}
<th scope="row"><a href="{{ model.admin_url }}">{{ model.name }}
{% if model.name == 'Newsletter' %}
<b style="color:red;">{{request.session.data.count}} New Email Added </b>
{% endif %}</a></th>
{% else %}
<th scope="row">{{ model.name }}</th>
{% endif %}
{% if model.add_url %}
<td><a href="{{ model.add_url }}" class="addlink">{% trans 'Add' %}</a></td>
{% else %}
<td> </td>
{% endif %}
模板
<form action="" method="post">
{% csrf_token %}
<input type="email" name="email" placeholder="Subscribe Our Newsletter" class="newsletter-box" required>
<button class="news-submit" type="submit">Join</button>
</form>