在选择选项中显示图像以供选择-Django Python [英] display images in select option for selection -Django Python

查看:51
本文介绍了在选择选项中显示图像以供选择-Django Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PRoject,并且卡在订单页面上.

在这里,我想在options标签中显示产品图片列表,以便用户可以从全部图片中选择一张图片,或者可以上传图片功能.

  • 我想向用户显示图像,以便用户可以选择其中之一.

models.py

  class产品(models.Model):prod_ID = models.AutoField(产品ID",primary_key = True)prod_Name = models.CharField(产品名称",max_length = 30,null = False)prod_Desc = models.CharField(产品说明",max_length = 2000,null = False)prod_Price = models.IntegerField(产品价格/件数",默认为0.00)prod_img = models.ImageField("Product Image",null = True)类ImageTemplate(models.Model):temp_id = models.AutoField(模板ID",primary_key = True,auto_created = True)temp_img = models.ImageField(模板图像",null = False)类ImageTemplateProductMapping(models.Model):imageTemp_p_map_id = models.AutoField(模板图像和产品地图ID",primary_key = True,auto_created = True)temp_id = models.ForeignKey(ImageTemplate,null = False,on_delete = models.CASCADE,verbose_name =图片模板ID")prod_id = models.ForeignKey(Product,null = False,on_delete = models.CASCADE,verbose_name =产品ID") 

views.py

  def顺序(请求,ID):产品= Product.objects.all()ImageTemplateProductsList = []尝试:ImageTemplateProductsMap = ImageTemplateProductMapping.objects.filter(prod_id = id)ImageTemplateProductsList = [data.temp_id.temp_img用于数据[ImageTemplateProductsMap]除了AttributeError:经过上下文= {'产品':产品,"ImageTemplateProductsList":ImageTemplateProductsList}返回render(请求,'user/order.html',上下文) 

order.html

  {%扩展了'user/layout/userMaster.html'%}{%标题%}订单{%endblock%}{%block css%}形式{位置:相对;}.tasksInput{右边距:150px;}标签{垂直对齐:顶部;}{%endblock%}{%块标题%}{%endblock%}{%封锁主要%}< div class =容器">< div>< div class =行舍入的mx-自动d块d-flex对齐内容中心"< button class ="btn btn-secondary my-2 mr-1">自定义</button>< button class ="btn btn-secondary my-2 ml-1"< Package</button></div>< div class ="row">< div class ="col-4">< div class =卡边界边界-次要">< div class ="卡主体mx-2 mt-4 mb-2>{%表示产品中的产品%}< a id =" {{product.prod_ID}}"class ="card-header"style ="font-size:5vw; color:black;"href =" {%url'user-order'product.prod_ID%}'>< h5 class ="h5"> {{product.prod_ID}}.{{product.prod_Name}}</h5></a>< div class =下拉分隔线"</div{%endfor%}</div></div></div>< div class ="col-8">< form>< div class =卡片mx-2 my-2 border border-secondary">< div class ="my-2">< div class ="form-group">< div class =表单组行mx-2"><标签为=数量";class ="form-control-label font-weight-bold card-header col-4 ml-4 my-auto".style ="background-color:#e3e4e6"< h5>数量:</h5</label><输入id =数量"class ="form-control col-5 mx-2 my-auto".类型=数字".</div></div>< div class ="form-group">< div class =表单组行mx-2">< label for =" ImageTemplateProductsList"class ="form-control-label font-weight-bold card-header col-4 ml-4".style ="background-color:#e3e4e6"< h5>图片模板:</h5></label>< div id =" ImageTemplateProductsList"class ="mx-2"< input id ="上传"type ="radio"name ="ImageSelection";value =上传"/>上载图像<输入类型=文件";名称=文件"class ='btn btn-outline-secondary type my-2'>< br>< input id =选择";type ="radio"name ="ImageSelection";值=选择"/选择从模板<!-按钮触发模式-><输入类型=按钮";name ="url"style ='display:none;'class ='btn btn-outline-secondary type my-2'value =选择模板"data-toggle ="modal"data-target =#exampleModalLong"<!-模态->< div class =模态淡入".id ="exampleModalLong"tabindex =-1";角色=对话";aria-labelledby ="exampleModalLongTitle"aria-hidden ="true"< div class =模态对话框";角色=文档"< div class =模态内容">< div class =模式标题">< h5 class =模态标题";id ="exampleModalLongTitle">选择模板</h5>< button type =按钮"class ="close"data-dismiss =模态".aria-label =关闭"< span aria-hidden ="true"& times;</span></button></div>< div class ="d-flex-row-justify-content-center modal-body"style =" background:red;>< div><!-在这里,我想在select标签中显示图像,以便从所有图像中选择一个,但无法实现.-><选择id =" ImageTemplateProductsList1>{%for ImageTemplateProductsList%中的IT}< option value =" {{IT}}>< img src =" {{IT.url}}"高度="250"宽度="400"class ="border border-secondary rounded my-2 mx-3".</option>< br>{%endfor%}</select></div>< div class =模态页脚">< button type =按钮"class ="btn btn-outline-danger";data-dismiss =模态">关闭</button>< button type =按钮"class ="btn btn-outline-secondary"选择</button></div></div></div></div>< br></div></div></div></div></div></form></div></div>< div class =行舍入的mx-自动d块d-flex对齐内容中心"< button class ="btn btn-success my-2"< Place Order</button></div></div></div>{%endblock%}{%阻止js%}$("document").ready(function(){$(.type").hide();$("input:radio").change(function(){$(.type").hide();$(this).next("input").show();});});{%endblock%} 

urls.py

  path('order/< int:id>',views.order,name ="user-order"), 

解决方案

我使用jquery略微修改了html模板,并稍微更改了视图,现在它对我有用.

order.html

  {%扩展了'user/layout/userMaster.html'%}{%标题%}订单{%endblock%}{%block css%}.t {显示:无;}img:悬停{不透明度:0.8;光标:指针;}img:活动{不透明度:0.5;光标:指针;}输入[type = radio]:已选中+标签>img {边框:20px实心rgb(228,207,94);}#落下{高度:50px;宽度:50%;font-size:20px;左边距:10px;页边距:3px;}{%endblock%}{%块标题%}{%endblock%}{%封锁主要%}< div class =容器">< div>< div class =行舍入的mx-自动d块d-flex对齐内容中心"< button class ="btn btn-secondary my-2 mr-1">自定义</button>< button class ="btn btn-secondary my-2 ml-1"< Package</button></div>< div class ="row">< div class ="col-4">< div class =卡片边框边界-次要">< div class ="卡主体mx-2 mt-4 mb-2>{%表示产品中的产品%}< a id =" {{product.prod_ID}}"class ="card-header"style ="font-size:5vw; color:black;"href =" {%url'user-order'product.prod_ID%}'>< h5 class ="h5"> {{product.prod_ID}}.{{product.prod_Name}}</h5></a>< div class =下拉分隔线"</div{%endfor%}</div></div></div>< div class ="col-8">< form method ="POST";enctype ="multipart/form-data".<输入类型=隐藏的".id ="templateValue"name ="templateValue"值="/{%csrf_token%}< div class ="form-group">< div class =表单组行mx-2">< label for =" ImageTemplateProductsList"class ="form-control-label font-weight-bold card-header col-4 ml-4".style ="background-color:#e3e4e6"< h5>图片模板:</h5></label>< div id =" ImageTemplateProductsList"class ="mx-2"< input id ="上传"type ="radio"name ="ImageSelection";class ="templateSelection"/>上载图像< div class ="type"><输入类型=文件";名称=图像"class ='btn btn-outline-secondary my-2 SelectedImage'></div>< br><输入类型=无线电".id =选择"name ="ImageSelection";class ="templateSelection"/>选择从模板< div class ="type">{%for ImageTemplateProductsList%中的IT}<输入类型=无线电".name ="image2"id ="{{IT}}"value ="{{IT}}"class ="SelectedImage t"/< label for =" {{IT}}>< img src =" {{IT.url}}"style ="width:20vw;高度:20vw;padding:2vw;"/";</label>< br>{%endfor%}</div></div></div></div></div></div>< div class =行舍入的mx-自动d块d-flex对齐内容中心"< button type =提交";class ="btn btn-success my-2">下订单</button></div></form></div></div></div></div>{%endblock%}{%阻止js%}$("document").ready(function(){$(.type").hide();$("input:radio").on('change',function(){$(.type").hide();$(this).next("div").show();});$(#templateValue").val('');$(.templateSelection").on('change',function(){$(#templateValue").val('');$(#templateValue").val($(this).attr('id'));console.log($(#templateValue").val());});});{%endblock%} 

我已经使用隐藏字段来检查用户是尝试上传图像还是选择tha图像,并据此做出我该怎么做的决定:

views.py

  def顺序(请求,ID):产品= Product.objects.all()ImageTemplateProductsList = []尝试:ImageTemplateProductsMap = ImageTemplateProductMapping.objects.filter(prod_id = id)ImageTemplateProductsList = [data.temp_id.temp_img用于数据[ImageTemplateProductsMap]除了AttributeError:经过如果request.method =='POST':尝试:如果request.POST ['templateValue'] =='上传':如果request.FILES中有图片":Template_Value1 = request.FILES ['image']fs = FileSystemStorage()fs.save(Template_Value1.name,Template_Value1)TemplateValue = Template_Value1.nameelif request.POST ['templateValue'] =='选择':TemplateValue = request.POST ['image2']别的:经过除了MultiValueDictKeyError:经过order_store =订单(product_img = TemplateValue)order_store.save()上下文= {'产品':产品,"ImageTemplateProductsList":ImageTemplateProductsList}返回render(请求,'user/order.html',上下文) 

I am working on a PRoject and I am stuck on order page.

Here, I want to display list of product images in options tag so that a user can select one image from all or can upload an image functionality of uploading image is working correctly but the selection is not working.

  • I want to show images to user so that user can select one of them.

models.py

class Product(models.Model):
    prod_ID = models.AutoField("Product ID", primary_key=True)
    prod_Name = models.CharField("Product Name", max_length=30, null=False)
    prod_Desc = models.CharField("Product Description", max_length=2000, null=False)
    prod_Price = models.IntegerField("Product Price/Piece", default=0.00)
    prod_img = models.ImageField("Product Image", null=True)

class ImageTemplate(models.Model):
    temp_id = models.AutoField("Template ID", primary_key=True, auto_created=True)
    temp_img = models.ImageField("Template Image", null=False)

class ImageTemplateProductMapping(models.Model):
    imageTemp_p_map_id = models.AutoField("Template Image & Product Map ID", primary_key=True, auto_created=True)
    temp_id = models.ForeignKey(ImageTemplate, null=False, on_delete=models.CASCADE,
                                verbose_name="Image Template ID")
    prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id")

views.py

def order(request, id):
    products = Product.objects.all()

    ImageTemplateProductsList = []
    
    try:
        ImageTemplateProductsMap = ImageTemplateProductMapping.objects.filter(prod_id=id)
        ImageTemplateProductsList = [data.temp_id.temp_img for data in
                                     ImageTemplateProductsMap]
    except AttributeError:
        pass

    context = {'products': products,
               "ImageTemplateProductsList": ImageTemplateProductsList
               }

    return render(request, 'user/order.html', context)

order.html

{% extends 'user/layout/userMaster.html' %}
{% block title %}Order{% endblock %}

{% block css %}
form
{
position:relative;
}
.tasksInput
{
margin-right:150px;
}
label
{
vertical-align: top;
}

{% endblock %}

{% block header %}
{% endblock %}
{% block main %}
<div class="container">
    <div>
        <div class="row rounded mx-auto d-block d-flex justify-content-center">
            <button class="btn btn-secondary my-2 mr-1">Custom</button>
            <button class="btn btn-secondary my-2 ml-1">Package</button>
        </div>
        <div class="row">
            <div class="col-4">
                <div class="card border border-secondary">
                    <div class="card body mx-2 mt-4 mb-2">
                        {% for product in products %}
                        <a id="{{ product.prod_ID }}" class="card-header" style="font-size:5vw;color:black;"
                           href="{% url 'user-order' product.prod_ID  %}">
                            <h5 class="h5">{{ product.prod_ID }}. {{ product.prod_Name }}</h5></a>
                        <div class="dropdown-divider"></div>
                        {% endfor %}
                    </div>
                </div>
            </div>
            <div class="col-8">
                <form>
                    <div class="card mx-2 my-2 border border-secondary">
                        <div class="my-2">
                            <div class="form-group">
                                <div class="form-group row mx-2">
                                    <label for="quantity"
                                           class="form-control-label font-weight-bold card-header col-4 ml-4 my-auto"
                                           style="background-color:#e3e4e6"><h5>Quantity : </h5></label>
                                    <input id="quantity" class="form-control col-5 mx-2 my-auto" type="number">
                                </div>
                            </div>

                            <div class="form-group">
                                <div class="form-group row mx-2">
                                    <label for="ImageTemplateProductsList"
                                           class="form-control-label font-weight-bold card-header col-4 ml-4"
                                           style="background-color:#e3e4e6"><h5>Image Template : </h5></label>
                                    <div id="ImageTemplateProductsList" class="mx-2">
                                        <input id="Upload" type="radio" name="ImageSelection" value="Upload"/> Upload an
                                        Image
                                        <input type="file" name="file" class='btn btn-outline-secondary type my-2'>
                                        <br>
                                        <input id="Select" type="radio" name="ImageSelection" value="Select"/> Select
                                        From Templates
                                        <!-- Button trigger modal -->
                                        <input type="button" name="url" style='display: none;'
                                               class='btn btn-outline-secondary type my-2'
                                               value="Choose Template" data-toggle="modal"
                                               data-target="#exampleModalLong">

                                        <!-- Modal -->
                                        <div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog"
                                             aria-labelledby="exampleModalLongTitle" aria-hidden="true">
                                            <div class="modal-dialog" role="document">
                                                <div class="modal-content">
                                                    <div class="modal-header">
                                                        <h5 class="modal-title" id="exampleModalLongTitle">Select
                                                            Template</h5>
                                                        <button type="button" class="close" data-dismiss="modal"
                                                                aria-label="Close">
                                                            <span aria-hidden="true">&times;</span>
                                                        </button>
                                                    </div>
                                                    <div class="d-flex-row justify-content-center modal-body"
                                                         style="background:red;">
                                                        <div>

<!-- Here I want to display images in select tag to make selection of one from all images but not able to achieve it. -->

                                                            <select id="ImageTemplateProductsList1">
                                                                {% for IT in ImageTemplateProductsList %}
                                                                <option value="{{IT}}"
                                                                ><img src="{{IT.url}}" height="250" width="400"
                                                                      class="border border-secondary rounded my-2 mx-3">
                                                                </option>
                                                                <br>
                                                                {% endfor %}
                                                            </select>
                                                        </div>
                                                        <div class="modal-footer">
                                                            <button type="button" class="btn btn-outline-danger"
                                                                    data-dismiss="modal">Close
                                                            </button>
                                                            <button type="button" class="btn btn-outline-secondary">
                                                                Select
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>

                                            <br>
                                        </div>
                                    </div>
                                </div>

                            </div>
                        </div>
                </form>
            </div>
        </div>
        <div class="row rounded mx-auto d-block d-flex justify-content-center">
            <button class="btn btn-success my-2">Place Order</button>
        </div>
    </div>
</div>

{% endblock %}

{% block js %}
$("document").ready(function(){
$(".type").hide();
$("input:radio").change(function() {
$(".type").hide();
$(this).next("input").show();
});
});
{% endblock %}

urls.py

path('order/<int:id>', views.order, name="user-order"),

解决方案

I have slightly modified my html template with jquery and changed views a little bit and now it is working for me.

order.html

{% extends 'user/layout/userMaster.html' %}
{% block title %}Order{% endblock %}

{% block css %}
.t {
display: none;
}

img:hover {
opacity:0.8;
cursor: pointer;
}

img:active {
opacity:0.5;
cursor: pointer;
}

input[type=radio]:checked + label > img {
border: 20px solid rgb(228, 207, 94);
}

#dropdown{
height: 50px;
width: 50%;
font-size: 20px;
margin-left: 10px;
margin-top: 3px;
}

{% endblock %}

{% block header %}
{% endblock %}
{% block main %}
<div class="container">
    <div>
        <div class="row rounded mx-auto d-block d-flex justify-content-center">
            <button class="btn btn-secondary my-2 mr-1">Custom</button>
            <button class="btn btn-secondary my-2 ml-1">Package</button>
        </div>
        <div class="row">
            <div class="col-4">
                <div class="card border border-secondary">
                    <div class="card body mx-2 mt-4 mb-2">
                        {% for product in products %}
                        <a id="{{ product.prod_ID }}" class="card-header" style="font-size:5vw;color:black;"
                           href="{% url 'user-order' product.prod_ID  %}">
                            <h5 class="h5">{{ product.prod_ID }}. {{ product.prod_Name }}</h5></a>
                        <div class="dropdown-divider"></div>
                        {% endfor %}
                    </div>
                </div>
            </div>
            <div class="col-8">
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" id="templateValue" name="templateValue" value=""/>
                    {% csrf_token %}
                             <div class="form-group">
                                <div class="form-group row mx-2">
                                    <label for="ImageTemplateProductsList"
                                           class="form-control-label font-weight-bold card-header col-4 ml-4"
                                           style="background-color:#e3e4e6"><h5>Image Template : </h5></label>
                                    <div id="ImageTemplateProductsList" class="mx-2">
                                        <input id="Upload" type="radio" name="ImageSelection"
                                               class="templateSelection"/> Upload an
                                        Image
                                        <div class="type">
                                            <input type="file" name="image"
                                                   class='btn btn-outline-secondary my-2 SelectedImage'>
                                        </div>
                                        <br>
                                        <input type="radio" id="Select" name="ImageSelection" class="templateSelection"
                                        /> Select
                                        From Templates
                                        <div class="type">
                                            {% for IT in ImageTemplateProductsList %}
                                            <input type="radio" name="image2" id="{{IT}}"
                                                   value="{{IT}}" class="SelectedImage t"/>
                                            <label for="{{IT}}">
                                                <img src="{{IT.url}}" style="width: 20vw;
                                                                             height: 20vw;
                                                                             padding: 2vw;"/>
                                            </label>
                                            <br>
                                            {% endfor %}
                                        </div>
                                    </div>
                                </div>

                            </div>
                        </div>
                    </div>
                    <div class="row rounded mx-auto d-block d-flex justify-content-center">
                        <button type="submit" class="btn btn-success my-2">Place Order</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block js %}

$("document").ready(function(){
$(".type").hide();
$("input:radio").on('change', function() {
$(".type").hide();
$(this).next("div").show();
});
$("#templateValue").val('');
$(".templateSelection").on('change', function(){
$("#templateValue").val('');
$("#templateValue").val($(this).attr('id'));
console.log($("#templateValue").val());
});
});


{% endblock %}

I have used hidden field to check whether user is trying to upload the image or select tha image and according to that I am taking the decision that what should I do:

views.py

def order(request, id):
    products = Product.objects.all()
    ImageTemplateProductsList = []

    try:
        ImageTemplateProductsMap = ImageTemplateProductMapping.objects.filter(prod_id=id)
        ImageTemplateProductsList = [data.temp_id.temp_img for data in
                                     ImageTemplateProductsMap]
    except AttributeError:
        pass

    if request.method == 'POST':
        try:
            if request.POST['templateValue'] == 'Upload':
                if 'image' in request.FILES:
                    Template_Value1 = request.FILES['image']

                    fs = FileSystemStorage()
                    fs.save(Template_Value1.name, Template_Value1)
                    TemplateValue = Template_Value1.name
            elif request.POST['templateValue'] == 'Select':
                TemplateValue = request.POST['image2']
            else:
                pass
        except MultiValueDictKeyError:
            pass
        order_store = Order(product_img=TemplateValue)

        order_store.save()
    context = {'products': products,
               "ImageTemplateProductsList": ImageTemplateProductsList
               }
    return render(request, 'user/order.html', context)

这篇关于在选择选项中显示图像以供选择-Django Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆