zoukankan      html  css  js  c++  java
  • Django的一些隐性经验

    隐性经验

    • 前后信息的沟通

    url中的参数 get获取 这个参数可以写在URL当中(可以写多个,写在这里的get函数需要有相应的参数去获取)。,也可以在模版中添加(通过?若是直接写则表示在当前的URL中添加,也可以在前面写动态的URL后边添加参数信息)
    post获取 post获取的主要是form表单中的信息,因此有个小技巧,form表单中可以有一些隐身的信息,是get渲染模版的时候传过来的

    # 以找回密码为例
    
    url('^reset/(?P<active_code>.*)/$', ResetView.as_view(), name='reset_pwd'),
    
    class ResetView(View):
        def get(self,request,active_code):
            all_recodes = EmailVerifyRecord.objects.filter(code=active_code)
            if all_recodes:
                for record in all_recodes:
                    email = record.email
                    #向模版中传入邮箱信息
                    return render(request,'password_reset.html',{
                        'email':email
                    })
            else:
                return render(request, 'active_fail.html')
            return render(request,'login.html')
            
    # html
     <input type="hidden" value="{{ email }}" name="email">
     
    # 因为form表单的action若是指向重置的链接,需要有一个参数,所以从新写了一个找回密码的类
    
    class ModifyPwdView(View):
        def post(self, request):
            modify_form = ModifyPwdForm(request.POST)
            if modify_form.is_valid():
                pwd1 = request.POST.get('password1', '')
                pwd2 = request.POST.get('password2', '')
                # 得到隐身的信息
                email = request.POST.get('email', '')
                if pwd1 != pwd2:
                    return render(request, 'password_reset.html',{
                        'email':email,
                        'msg':'密码不一致'
                    })
                user = UserProfile.objects.get(email=email)
                user.password = make_password((pwd2))
                user.save()
                return render(request, 'login.html')
            else:
                email = request.POST.get('email', '')
                return render(request, 'password_reset.html', {
                    'email': email,
                    'modify_form':modify_form
                })
    
    • 模版中无法判断是否为选中状态,可以在后端中添加一个字段,传到前端做区分
    # view
    current_page = 'home'
    
    # html
    class="{% if current_page == 'home' %}active2{% endif %}"
    
    
    • 模板中需要一些数据库的逻辑处理,可以通过在model中直接添加函数,也可以通过自定义标签和过滤器来实现.

    • 在含有基层和高层的app的时候要灵活的使用它们之间的联系,要那个类中含有这个外键字段,那么就可以通过这个字段的set找到那个类的信息.

        def get_learn_users(self):
            return self.usercourse_set.all()[:5]
    
    • 模板中是for循环,但是若后台传递一个空的字符串会报错的.如果是空,应该传递一个空列表才行.
  • 相关阅读:
    [原创]基于asp.ent MVC的无刷新文件上传组件
    ATL 开发 Com 学习笔记
    杀毒软件—美杜杉(medusa)使用观后感1
    IIS gzip压缩
    常用网页播放器代码
    [转]安装AspNetMVC1RC2出错
    Asp.net 异步请求 IHttpAsyncHandler
    发几个小的测式软件
    [转]关于document.cookie的使用
    boost Serialization
  • 原文地址:https://www.cnblogs.com/NeedEnjoyLife/p/6943373.html
Copyright © 2011-2022 走看看