Django 学习笔记二
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django 学习笔记二相关的知识,希望对你有一定的参考价值。
通过邮件分享post
django创建表单
from django import forms class EmailPostForm(forms.Form): name = forms.CharField(max_length=25) email = forms.EmailField() to = forms.EmailField() comments = forms.CharField(required=False, widget=forms.Textarea)
在视图中处理表单
from django.core.mail import send_mail def post_share(request, post_id): # Retrieve post by id post = get_object_or_404(Post, id=post_id, status=‘published‘) sent = False if request.method == ‘POST‘: # Form was submitted form = EmailPostForm(request.POST) if form.is_valid(): # Form fields passed validation cd = form.cleaned_data post_url = request.build_absolute_uri( # 获取FQDN的url地址 有http和主机地址 post.get_absolute_url()) subject = ‘{} ({}) recommends you reading "{}"‘. format(cd[‘name‘], cd[‘email‘], post.title) message = ‘Read "{}" at {}\n\n{}\‘s comments: {}‘. format(post.title, post_url, cd[‘name‘], cd[‘comments‘]) send_mail(subject, message, ‘[email protected]‘, [cd[‘to‘]]) sent = True else: form = EmailPostForm() return render(request, ‘blog/post/share.html‘, {‘post‘: post, ‘form‘: form, ‘sent‘: sent})
在django中发送邮件
在setting中添加
EMAIL_BACKEND = ‘django.core.mail.backends.smtp.EmailBackend‘
EMAIL_HOST = ‘smtp.163.com‘
EMAIL_HOST_USER = ‘[email protected]‘
EMAIL_HOST_PASSWORD = ‘XXXXXX‘
EMAIL_USE_TLS = True
在django shell 中测试
from django.core.mail import send_mail
>>> send_mail(‘Django mail‘, ‘This e-mail was sent with Django.‘,
‘[email protected]‘, [‘[email protected]‘, # 需要发送的邮件列表], fail_
silently=False)
增加tag标签
安装tag应用
pip install django-taggit
编辑settings.py文件 添加INSTALLED_APPS
‘taggit‘,
本文出自 “Linux is belong to you” 博客,请务必保留此出处http://jwh5566.blog.51cto.com/7394620/1750523
以上是关于Django 学习笔记二的主要内容,如果未能解决你的问题,请参考以下文章