4.主页搜索,发布页面,商品详情动态显示

1.主页显示

登陆成功之后传两个参数,用户id和用户名称到主页动态显示到主页右侧,

image

变为

image

views.py中代码:

 user_id = request.session.get('userid')
 nick_name = request.session.get('nick_name')

index主页代码:

  {% if nick_name == None %}
            {#头部用户#} 注册
            {#头部退出#} 登录
        {% else %}
            {#头部用户#} {{ nick_name }}
            {#头部退出#} 退出
        {% endif %}

主页显示效果

image

views.py部分代码:

def welcomeToIndex(request):
    user_id = request.session.get('userid')
    nick_name = request.session.get('nick_name')
    if user_id is not None:
        user = User.objects.get(id=user_id)
        goods_list = Goods.objects.filter().exclude(user=user).order_by('-create_time')
    else:
        goods_list = Goods.objects.filter().order_by('-create_time')
    return render(request, 'index.html', {"goods_list": goods_list, "nick_name": nick_name})

主页部分代码:循环goods_list,显示其中内容

{#分页#}
{% for foo in goods_list %}

¥{{ foo.price }}

{% endfor %}

2.主页模糊搜索

1.模糊搜索效果

image

2.views.py部分代码

__contains是用来模糊搜索的,注意两个下划线!!!

def search(request):
    flag = 1
    key = request.GET.get("key")
    print("key" + key)
    nick_name = request.session.get('nick_name')
    goods_list = Goods.objects.filter(name__contains=key).order_by('-create_time')
    return render(request, 'index.html', {"goods_list": goods_list, "nick_name": nick_name})

3.函数部分

  function search_key() {
         var key = $("#input_pass").val();
         window.location.href = "search?key=" + key;
    }

3.发布页面后台

1.图片处理

点击上传图片,选中图片,页面上显示图片,并且uuid函数处理图片,生成不重复的图片名字存到media文件夹

1.效果图


image.png

2.文件选中图片改变,显示在页面上,部分代码:

 $(function () {
        layui.use(['layer', 'form'], function () {
            var layer = layui.layer
                , form = layui.form;
            form.render();
        });
        $("#action_show_goods").change(function () {
            var $file = $(this);
            var fileObj = $file[0];
            var windowURL = window.URL || window.webkitURL;
            var dataURL;
            var $img = $("#img_show");
            if (fileObj && fileObj.files && fileObj.files[0]) {
                dataURL = windowURL.createObjectURL(fileObj.files[0]);
                $img.attr('src', dataURL);
            } else {
                dataURL = $file.val();
                var imgObj = document.getElementById("preview");
                // 两个坑:
                // 1、在设置filter属性时,元素必须已经存在在DOM树中,动态创建的Node,也需要在设置属性前加入到DOM中,先设置属性在加入,无效;
                // 2、src属性需要像下面的方式添加,上面的两种方式添加,无效;
                imgObj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
                imgObj.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = dataURL;

            }
        });
    });

3.创建media文件和app同等级
在url中加入

   re_path(r'^media/(?P.*)$', serve, {'document_root': MEDIA_ROOT}),

setting.py里面加入:

MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')  # 设置静态文件路径为主目录下的media文件夹
MEDIA_URL = '/media/'  # url映射

views.py中代码

# 利用UUID生成不重复的图片名,避免上传相同的名字的图片被覆盖
def do_file_name(file_name):
    return str(uuid.uuid1()) + os.path.splitext(file_name)[1]

2.ajiax form提交

views.py部分代码如下:
用为是ajax提交,加上@csrf_exempt

@csrf_exempt
def issue_form(request):
    flag = 0
    if request.method == "POST":
        # 里面的参数是name
        goods_name = request.POST.get("goods_name")
        print(goods_name)
        goods_detal = request.POST.get("goods_detal")
        print(goods_detal)
        goods_price = request.POST.get("goods_price")
        print(goods_price)
        categorys = request.POST.get("categorys")
        print(categorys)
        transactionMode = request.POST.get("transactionMode")
        print(transactionMode)
        address = request.POST.get("address")
        print(address)
        pho_num = request.POST.get("pho_num")
        print(pho_num)
        qq_num = request.POST.get("qq_num")
        print(qq_num)
        wechat_num = request.POST.get("wechat_num")
        print(wechat_num)
        file_img = request.FILES.get('file_img')
        print(file_img.name)
        print(file_img.size)
        file_chunks = file_img.chunks()
        # 文件保存的路径
        # /images/qwyuqguweuq.jpg
        file_name = os.path.join("images", do_file_name(file_img.name)).replace('\\', '/')
        # 完整的路径
        file_path = os.path.join(settings.MEDIA_ROOT, file_name).replace('\\', '/')
        with open(file_path, "wb")as file:
            for chunk in file_chunks:
                file.write(chunk)
        new_issue = Goods()
        new_issue.name = goods_name
        new_issue.detal = goods_detal
        new_issue.price = goods_price
        new_issue.master_pho = pho_num
        new_issue.master_qqnum = qq_num
        new_issue.master_wechatnum = wechat_num
        new_issue.trading = transactionMode
        userid = request.session.get('userid')
        new_issue.user = User.objects.get(id=userid)
        sort = Sort.objects.get(id=categorys)
        print(sort.__dict__)
        new_issue.sort = sort
        new_issue.img = file_name
        try:
            new_issue.save()
            flag = 1
        except Exception as e:
            print(e)
    return HttpResponse(flag)

发布页面ajax函数部分代码:

  function issue() {
        var formData = new FormData($("#goods_form")[0]);
        ;
        if ($("goods_name").val() == "") {
            layer.msg("请输入商品名称");
            return;
        }
        if ($("#goods_price").val() == "") {
            layer.msg("请输入价格");
            return;
        }
        if ($("#pho_num").val() == "") {
            layer.msg("请输入电话");
            return;
        }
        $.ajax({
            type: "POST",
            url: "issue_form",
            {#上传表单#}
            data: formData,
            dataType: "json",
            processData: false,
            contentType: false,
            success: function (data) {
                console.log(data);
                if (data == 1) {
                    layer.msg("发布成功");
                }
                else if(data == 0) {
                    layer.msg("数据储存失败");
                }
            },
            error: function () {
                layer.msg("发生未知错误");
            }
        });
    }

4.商品详情页动态显示

显示效果图


image.png

views.py部分代码如下:

def togood_detail_page(request):
    nick_name = request.session.get('nick_name')
    id = request.GET.get('id')
    print("id: " + id)
    goods_detal = Goods.objects.get(id=id)
    return render(request, "good_detail_page.html", {"goods_detail": goods_detal, "nick_name": nick_name})

显示代码,花括号显示出来即可,注意{{ MEDIA_URL }}文件目录怎么写
举个例子:

 

发布于:{{ goods_detail.create_time }}

{{ goods_detail.name }}

5.登出

views.py部分代码如下:

def logout(request):
    del request.session["nick_name"]
    del request.session["userid"]
    return HttpResponseRedirect("index")

你可能感兴趣的:(4.主页搜索,发布页面,商品详情动态显示)