这种技术可以在数据库中创建表,但是我不想在数据库中创建表。
class Email(models.Model):
to = models.EmailField(null = False)
subject = models.CharField(max_length = 255, null = False)
message = models.TextField(max_length = 555, null = False,)
class EmailAdmin(admin.ModelAdmin):
list_display = ('to','subject','message',)
#Here i can send emails to users.
def save_model(self, request, obj, form, change):
#I commented this line because i don't want to store this model into database.
#super(MyAdminView, self).save_model(request, obj, form, change)
admin.site.register(Email,EmailAdmin)
还有其他解决方法吗?
答案 0 :(得分:0)
您似乎需要使用自己的自定义表单,视图和模板添加新的管理网址:
from django.core.mail import send_mail
class EmailForm(forms.Form):
subject = forms.CharField()
message = forms.CharField()
to = forms.EmailField()
def send_email(self):
send_mail(
self.cleaned_data.get('subject'),
self.cleaned_data.get('message'),
'from@example.com',
[self.cleaned_data.get('to')],
fail_silently=False,
)
class SomeAdmin(admin.ModelAdmin): # You need to override an ModelAdmin
def get_urls(self):
urls = super().get_urls()
my_urls = [
path('my_view/', self.my_view),
]
return my_urls + urls
def my_view(self, request):
if request.method == "GET":
return render(request, 'template.html', {'form': EmailForm()}
else:
form = EmailForm(request.POST)
if form.is_valid():
form.send_email()
# rest of your view
# Template
{% extends "admin/base_site.html" %}
{% block content %}
<form method="post">
{% csrf_token %}
{{ form.as_p }}
</form>
{% endblock %}
请参阅here中的文档。