赞
踩
####1.NewUser继承AbstractUser出现错误: HINT: Add or change a related_name argument to the definition for 'NewUser.user_permissions' or 'User.user_permissions'
解决方案:在settings.py中加入申明
AUTHUSERMODEL = "MyApp.NewUser
####2.在进行超级用户生成(python manage.py createsuperuser
)报错django.db.utils.IntegrityError: (1048, "Column 'img_id' cannot be null")
解决方案:错误原因在生成超级用户,控制台输入字段只有用户名,密码,邮箱;所以NewUser在继承AbstractUser时,添加新的属性,就要求
null=True
####3.问题说明:在Django后台开发的时候,个人想采用前端框架bootstrapped,就直接在项目目录下cmd,直接采用命令pip install django_admin_boostrapped
之后,发现项目bug,报错如下:HINT: Django 1.7 changed the global defaults for the MIDDLEWARE_CLASSES. django.contrib.sessions.middleware.SessionMiddleware, django.contrib.auth.middleware.AuthenticationMiddleware, and django.contrib.messages.middleware.MessageMiddleware were removed from the defaults. If your project needs these middleware then you should configure this setting.
。
百度半天之后进行分析发现是中间件的问题。
解决方案:
(1) 先确定自己使用Django的版本。
(2) Django1.9和以前版本:采用
MIDDLEWARE_CLASSES = (
'zqxt.middleware.BlockedIpMiddleware',
...其它的中间件)
,而在1.10版本及以上MIDDLEWARE=( )
####4.在头像上传之后,想显示一张图片,而非显示一个图片地址
解决方案:在urls.py配置
urlpatterns = [
url('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 。
在这里需要注意导入文件
from django.conf.urls.static import static
和from django.conf import settings
####5.在进Admin后台添加富文本编辑器,按着网上教程出错[08/Mar/2018 09:33:43] "GET /static/js/kindeditor/config.js HTTP/1.1" 404 1682
解决方案:
(1)先将文件拷进去static/js,接着在admin.py中想添加文本编辑器的class下,加入基础配置,网上可查看;
(2)新增config.js,并进行相应的配置;
(3)在setting.py中配置STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
####6.在Admin中进行搜索配置的时候,报错Related Field got invalid lookup: icontains
错误分析:出现这个错误的时候,意思是你搜索的条件是一个实体,也就是说你在搜索这个字段;其实这个字段参照其它的实体(即外键约束)
解决方案:你查询字段__具体属性
;这边注意下划线是两段;
实例:models.py中
column = models.ForeignKey(Column, blank=True, null=True, verbose_name='分类', on_delete=models.CASCADE)
在admin.py中
search_fields = ('title', 'column__name',)
####7.在Django中进行用户名是否存在时候,从数据库进行数据读取注意数据格式,通过print输出[{'username': 'hdq'}, {'username': 'hq521'}, {'username': 'ls'}, {'username': '清风'}, {'username': '落俗'}]
字典形式,读取时候需注意
解决方案:具体看字典读取数据方式。例子:
name = name['username']
####8.在Django开发过程中,出现错误HTTP 错误 500.0 - Internal Server Error
解决方案:
1.查看urls.py文件,其中可以将url(r'^user_exist/$', views.user_exist),
去掉‘/$’
2.注意.py文件,有可能语法出错
####9.在Django开发中如果多处用到富文本框需要注意,文本框名字需统一,方便富文本框的使用
####10.在开发中有可能出现一些链接外网样式,会加载不到资源或者加载很慢;
解决方案:
1.先复制链接,在访问,将其全部复制
2.在项目先对应的地方新建该类型文件,将页面链接地址,改成本地即可
####11.bug:cannot convert dictionary update sequence element #0 to a sequence
解决方案:个人的错误原因是在views.py与html页面进行数据交互时,代码
return render(request, “index.html”, context)
方案1:
return render(request, "index.html", {'context': context})
方案2:
context{
'images': images,
}
return render(request, "index.html", context)
####12.在Django页面开发,采用原生SQL进行复杂数据库查询,查询不到数据原因分析
解决方案:使用管理器来执行原生SQL,在涉及多表的就不能进行查询。代码如下:
blog_comment = Blog.objects.raw("SELECT * FROM myblog_blog ORDER BY (SELECT COUNT(comBlog_id) FROM myblog_comment WHERE myblog_comment.comBlog_id = myblog_blog.id) DESC LIMIT 1")
可采用游标方式就行读取代码如下:
获取评论数最高、最新的博客
cursor = connection.cursor()
cursor.execute("SELECT * FROM myblog_blog ORDER BY (SELECT COUNT(comBlog_id) FROM myblog_comment WHERE myblog_comment.comBlog_id = myblog_blog.id) DESC LIMIT 1")
blog_comment = cursor.fetchone()
####13.在Django项目开发中,数据读取不到,检查views.py。发现
blog_most = Blog.objects.filter(id=blog_comment_id)
####将其输出打印发现打印“[ < Blog: 城堡 > ]”,为list类型,可通过for循环遍历。正确应该为“城堡”
解决方案:
blog_most = Blog.objects.get(id=blog_comment_id)
####14.在Django开发中,需要将一个实体类中,封装进一个字段;假设说明,我有一个博客model(实体),并查处其相应的的评论数
解决方案:上实际代码:
在view.py上实现
blog_counts = Blog.objects.all().count()
if blog_counts is not None:
random_num = random.randint(1, blog_counts)
if random_num == 1:
random_blog = Blog.objects.all()[:1]
else:
random_blog = Blog.objects.all()[random_num - 2:random_num]
list_blog = []
for blog in random_blog:
blog_comments = Comment.objects.filter(comBlog_id=blog).count()
list_blog.append([blog, blog_comments])
在html页面上代码实现
<div class="row"> {% for blog in list_blog %} <div class="col-sm-6"> <article class="entry-item"> <div class="entry-header"> <a href="#" class="entry-category">{{ blog.0.column }} </a> <h2 class="entry-title"> <a href="/blog/single">{{ blog.0.title }}</a> </h2> </div> <div class="entry-wrap"> <div class="entry"> <div class="entry-content"> <p> {% autoescape off %} {{ blog.0.content }} {% endautoescape %} </p> </div> <div class="entry-meta-wrap clearfix"> <ul class="entry-meta"> <li class="entry-date"> <a href="#">{{ blog.0.create_date | date:"F j, Y"}}</a> </li> <li class="entry-comments"> <a href="/blog/single">评论 {{ blog.1 }} </a>
####15.在引用一些插件的js时候,发现一直报错,检查不出错误时候,请注意一些js引用的顺序问题;一般情况jQuery的引用发在最前面
####16.在Django进行数据库数据插入涉及外键,数据插入一直报错,控制台报错为:INTERNAL SERVER ERROR
;
解决方案:
1.打印输出传入的值,打印输入为[{'username': 'hdq'}]
,说明获得值的方式有问题如果是采用filter获得值,则改为get。使用filter取得的数据为列表类型(可直接采用if 列表来判断是否为空),使用get则得到一个对象
2.将整个获得的model直接传入(并不需要获得id,在将id传入)
####17.在Django ajax提交出现点击一次提交,却出现了数据提交两次
解决方案:
1.不使用type为submit类型的按钮,而是采用type是button的按钮;因为submit有默认提交的行为
2.在函数的最后一行返回return false
即可
####18.在Djano模板 实现奇偶计数判断
解决方案:
{%if forloop.counter|divisibleby:2 %}
<ul class="comment-list">
{% else %}
<ul class="comment-reply">
{% endif %}
####19.在Django开发中要注意链接问题直接上代码
代码
html页面
{# /blog/send_email/ 注意‘/’,因为这个‘/’,views一直取不到值#}
url: ‘/blog/send_email/’,
####20.在进行邮件(采用STMP)发送模块开发需要注意
- 先确定自己是否要自己搭建STMP服务器,一般是使用已有的大公司服务器(个人采用QQ的)
- 确定好所使用的STMP服务器之后,要确定好发送方,接受方。一般为了保护用户隐私,可在代码中嵌入第三方代发邮件。
- 在使用先对应的服务器必须确定相应的端口号
- 在邮件发送的时候要注意去配置STMP的服务,在配置生成动态码,用在口令中
直接上代码:
# 邮件发送 def send_email(request): message = '发送失败' if request.method == 'POST': if request.is_ajax(): name = request.POST['name'] email = request.POST['email'] title = request.POST['title'] content = request.POST['contact'] sender = '********@qq.com' print(sender) content = content + ";回复联系:" + email # 接受邮件 receivers = ['********@qq.com'] # 第三方服务 mail_host = "smtp.qq.com" # 设置服务器 mail_user = "********@qq.com" # 用户名 mail_pass = "********" # 口令 # 邮件内容 message_email = MIMEText(content, 'plain', 'utf-8') message_email['Form'] = Header(name, 'utf-8') message_email['To'] = Header('凌尘', 'utf-8') message_email['Subject'] = Header(title, 'utf-8') try: sftp_email = smtplib.SMTP_SSL(mail_host) sftp_email.set_debuglevel(1) sftp_email.ehlo(mail_host) sftp_email.login(mail_user, mail_pass) sftp_email.sendmail(sender, receivers, message_email.as_string()) print('邮件发送成功') except smtplib.SMTPException: print("Error: 无法发送邮件") message = '发送成功' return HttpResponse(message) else: return HttpResponse(message) else: return HttpResponse(message)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。