Django中遇到的坑(长期更新)

1.Django分页出现UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered ob

messeges = MessegeModel.objects.all()

变为

messeges = MessegeModel.objects.get_queryset().order_by('id')
2.ajax提交表单403:
data: {'content':content,"csrfmiddlewaretoken":$("[name='csrfmiddlewaretoken']").val()}
3.ajax返回值未序列化:

1.序列化Quset对象

pictures = AlbumModel.objects.all()
            data['pictures'] = serializers.serialize('json', pictures)
            return JsonResponse(data)

在js中要进行反序列化的操作:
var formData = new FormData($("#form")[0]);

2.序列化单个实例(model)

user = simplejson.loads(serializers.serialize('json', [user])[1:-1])

4.Specifying a namespace in include() without providing an app_name '
django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead.

这是url中的`include的问题,这样写

url(r'^reviews/', include(('reviews.urls', 'reviews'), namespace='reviews'))

5.无法导入模块ImportError: cannot import name 'simplejson'
首先检查pip版本是不是用的python3pip3,因为python3自带了pip3,所以可以创建一个pip3的软连接

ln -s /usr/local/python3/bin/pip3 /usr/bin/pip
(我的pip3在/usr/local/python3/bin/pip3,可以通过whereis查看)
4.xshell推出后django后台程序也被关闭

解决方法:

在启动项目的时候nohup python manage.py runserver 0.0.0.0:80

5.更新数据库的数据出现'BlogModel' object has no attribute 'update'

不直接对数据库进行update操作

 current_blog = BlogModel.objects.get(id=blog_id)
 current_blog.blog_name = blog_name
 current_blog.blog = blog
 current_blog.blog1 = blog1
 current_blog.save(update_fields=['blog_name','blog','blog1'])
6.网页加载缓慢

如果页面加载项不是很多,那么问题或许出现在方法里面,试着用原生sql语句替代ORM
blogs = BlogModel.objects.get_queryset().order_by('id')这句话用ORM语句查询可能用时是blogs = BlogModel.objects.raw(sql)的十倍以上。
注意使用原生语句查询的结果是<class 'django.db.models.query.RawQuerySet'>所以再继续对他进行操作可能先处理一下,比如我这里做一个分页就需要先将结果转换为列表paginator = Paginator(list(blogs), 15)

7.表单提交多个相同字段的值

如果要提交下面这种name相同的多个值的表单:

<form>
  <input type = "text" name="user" value="1">
  <input type = "text" name="user" value="2">
  <input type = "text" name="user" value="3">
  <input type = "submit" value = "submit">
</form>

在后端应该这样接受参数:

    if request.method =='POST':
        names = request.POST.getlist('user[]')
  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值