Python学习过程遇到的坑-项目(2)

1.用户登录代码已经注释

# 用户登录
def login(request):
    # get请求获取登录页面
    if request.method == 'GET':
        return render(request, 'xym/login.html')

    # post请求获取信息
    if request.method == 'POST':
    #the username and account is just a name,you can use any name,
    #butthe account name has to be the same like the html file
        username = request.POST.get('account') # because is name='account' in html
        password = request.POST.get('password')
        print(username)#we can print the username if we want to see what it is
        print(password)

        # 判断账号是否存在
        if User.objects.filter(account=username).exists(): # chec kif the user exist
            #users这个QuerySet对象存储了用户的所有信息
            users = User.objects.filter(account=username)  # 获取的是列表类型 # get row from database, index 0 because 1 result

            # 检查密码,users.password获取用户密码
            # if check_password(password, users[0].password): # check the hashed password of the user
            #由于数据库中密码没有使用hash加密,所以直接按下面的方法取判断密码是否正确
            if password == users[0].password:

                # 将登录的账户名传递给session对象

                request.session['account'] = username # store user into session after login
                request.session['pika_data']=123
                request.session['user_id'] = users[0].user_id
                # session is server side database
                return HttpResponseRedirect('/xym/addnewhouse/')
            else: # wrong password
                return HttpResponse('登录密码错误')
        else: # wrong user
            return HttpResponse('登录账号错误')
代码中相关知识:对象检索

​ 对数据库中对象的检索,是通过model Manage来构造一个QuerySet对象来实现的。每个model类都有一个Manage方法,model类通过objects来调用Manage方法。model对象中没有objects属性。QuerySet对象对象是一个model类对应的实例集合,及数据库对应表的子集。

  • ​ 检索所有的对象:

    ​ 查找model类对应表总的所有对象(数据),是通过all方法来实现,其返回一个QuerySet对象。

    
    #可以获取Entry模型中所有对象,要什么都可以通过all_entries点出来
    
    all_entries = Entry.objects.all()
  • 通过filter检索特定对象

    ​ 通常查询数据库只是检索对应表中的一条或几条数据,其主要通过两种方法来实现。

    • filter

    通过filter中的条件(kwargs)进行数据库查询,返回一个QuerySet对象。

    用法举列:

    
    #返回的QuerySet对象中只包含name='paul'的对象
    
    Author.objects.filter(name='paul)
    • exclude(**kwargs)

    通过exclude中的条件,排除特定的数据,返回表中剩余的数据,返回数据是一个QuerySet对象。

    用法举例:

    
    #返回QuerySet对象中,不包含name='pual'的model对象
    
    Author.objects.exclude(name='paul)
    • filter和exclude不仅可以单独使用,还可以级联进行使用。

    用法举例:

    
    #查找 entry 中 headline 由 What 开头, 不是今天发布的, 发布日期大于 2018/07/08的数据, 共三个条件。
    
    Entry.objects.filter(headline_startwith='what').exclude(pu_data__gta=datetime.fata.today()).filter(pub_data_gte=datetime(2018,7,8))

    `以上所列的三个条件最红会整合成一条SQL语句去执行。相当于:

    select * from entry where headline LIKE 'what%' AND NOT pub_date='2018.3.7'  and pu_data>'2017.7.8'
    • 每个filter返回的对象都是不相关的。

    每次生产的QuerySet对象都是相互独立的,可以保存或者重复使用。

    q1 = Entry.objects.filter(headline_startwith='what')
    
    q2 = q1.exclude(pud_data__gte.data.today())
    
    q3 = q1.filter(pud_data__gte=datetime.date.today())
    • QuerySet懒加载

    ​ 懒加载的意思是QuerySet对象在创建的时候不会执行数据库查询操作,只有在使用这个对象式下回进行数据库查询操作。

     q1 = Entry.objects.filter(headline_startwith='waht')
    
      q2 = q1.exclude(pud_data__gte.data.today())
    
      q3 = q1.filter(pud_data__gte=datetime.date.today())
      #以上三次不会执行数据库查询操作,在print的时候才会执行。
      print(q)
    
    

    更多使用操作方法参考:https://www.cnblogs.com/zhaoyingjie/p/6984957.html

    2.登录页面前端脚本

    
    #form表单的请求方式method='POST',执行的页面test:login.
    
    <form method="post" action="{% url 'test:login' %}">
        #表单提交的时候,为防止跨站攻击,需要添加{% csrf_token %}  
            {% csrf_token %}  
         <fieldset>
              <p class="mt20">
                #the account will be ge by the python
                <input type="text" name= 'account' placeholder="用户名/手机" class="lg_input01 lg_input">
              </p>
                   <p class="mt20">
                <input type="text" name='password' placeholder="密码" class="lg_input02 lg_input">
              </p>
                  <p class="clearfix lg_check"><span class="fl"><input type="checkbox">记住用户名</span><a href="#" class="fr">忘记密码?找回</a></p>
                  <!--<p><a href="test/index" class="lg_btn">立即登陆</a></p>-->
                  #submit will 
                   <input type="submit" class="btn btn-success" value="立即登陆">
         </fieldset>
    </form>

    3.get the user information from the login part

    part1-code of the login part:
    request.session['pika_data']=123
    request.session['account'] = username # store user into session after login
    request.session['user_id'] = users[0].user_id
    
    # session is server side database
    
    
    
    
    #下面的方法可以直接获取到login函数中的相关信息
    
    part2-code of other function that need to get the user information:
    
    #在code1中123存储在pika_data这个名字中,我们用下面这个方法去拿pika的全部信息
    
    pika=request.session.get('pika_data') # pika will be equal to 123 now
    
    
    # OPTION A
    
    
    # this is different website, we want to get session
    
    
    #在code1中username存储在account这个名字中,我们用username.+关键字的方法去拿username的全部信息
    
    username = request.session.get('account') # get username from session, we need to login first !!!
    
    
    # after session we check database for user_id for username
    
    
    #获取数据库中account等于username的全部信息。即将符合account=username条件的账号全部取出来,结果返回的式一个QuerySet对象
    
    users = User.objects.filter(account=username) # search database,  get users from database with username user
    
    
    #上面已经取出了account=username的全部信息,接下来我们只需要取出第一个值就可以
    
    
    #user.user_id可以从上面users这个QuertSet对象中取出想要的字段。如果想取password,:users.password
    
    user_id=users[0].user_id # we get user_id from first one (row 0, always 0)
    
    
    # OPTION B
    
    
    
    #another way to get user id (faster, no database)
    
    
    #user_id = request.session.get('user_id') # after login
    

    4.当models中没有icon,如何将上传的图片保存在本地

    option A:
    
    # 房屋图片
    
          img_file = request.FILES.get('house_image')
          fs = FileSystemStorage()
          filename = fs.save(img_file.name, img_file)
          index_img_url=fs.url(filename)
    
    
    oprtion B:
            img_file = request.FILES.get('house_image')
          img = Image.open(img_url)
          img.save('media/%s' % img_url)
          im_url = '/media/' + str(img_url)
    
    
    

    5.图片可以成功上传,但是显示处一直显示为icon

    解决办法:

    https://www.cnblogs.com/52forjie/p/7875875.html

    from django.views.static import serve  #需要导入
    url(r'^media/(?P<path>.*)$', serve, {'document_root':settings.MEDIA_ROOT}),  #这部分很重要

    6.提交表单后如何删除

    $('#form-id').submit(function(){
      // send data to server (views.py)
      var formData = new FormData(this);
      $.post('/xym/addnewhouse/', formData, function(data){
      });
    
      return false;
    });
    HouseDetail.objects.filter(house_id=houses).delete() # remove the house from table, where house_id is foreign key
    HouseFacility.objects.filter(house_id=houses).delete() # remove the house from table, where house_id is foreign key
    HouseImg.objects.filter(house_id=houses).delete() # remove the house from table, where house_id is foreign key
    House.objects.filter(house_id=houses).delete() # at last we remove the house from main table, where house_id is MAIN key

7.app’ is not a registered namespace

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

猜你喜欢

转载自blog.csdn.net/u014229742/article/details/80989180
今日推荐