繁体   English   中英

将表单的多个输入值存储在单个 json 中以存储在 model 字段中。 - Django

[英]Store multiple inputs values of form in single json to store in model field. - Django

我正在从事一个在线打印订购服务的项目。

在订单页面上,我在表单的单选按钮列表中获得了产品的不同属性,以及我想要存储在数据库中的单个 json 中的所有属性。

模型.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)

    def __str__(self):
        return "{}-->{}".format(self.prod_ID,
                                self.prod_Name)


# this is the order table , there is a "attribute_field" I wantto store the attributes in this field 
# as JSON.
class Order(models.Model):
    order_id = models.AutoField("Order ID", primary_key=True)
    user_id = models.ForeignKey(User, on_delete=models.CASCADE, null=False, verbose_name="Customer ID")
    prod_id = models.ForeignKey(Product, on_delete=models.CASCADE, null=False, verbose_name="Product ID")
    quantity = models.ImageField('Product Quantity', max_length=10, default=500)
    attribute_value = models.CharField("Item Details JSON", max_length=2000, null=False)
    order_date = models.DateField("Order Date", auto_now_add=True, null=False)
    order_job_title = models.CharField("Name of Company/Business", max_length=100, null=False)
    order_desc = models.CharField("Details for Product", max_length=1000, null=False)
    product_img = models.ImageField("Template Image", null=False)
    address = models.CharField("Customer Address ", max_length=100, null=False)
    state = models.CharField("Customer State", max_length=30, null=False)
    city = models.CharField("Customer City", max_length=30, null=False)
    postal_code = models.IntegerField("Area Pin Code", null=False)
    order_price = models.DecimalField(max_digits=8, decimal_places=2, default=0000.00)    

class Size(models.Model):
    size_id = models.AutoField("Size ID", primary_key=True, auto_created=True)
    prod_size = models.CharField("Product Size", max_length=20, null=False)

    def __str__(self):
        return "{size_id}-->{prod_size}".format(size_id=self.size_id,
                                                prod_size=self.prod_size)


class Color(models.Model):
    color_id = models.AutoField("Color ID", primary_key=True, auto_created=True)
    prod_color = models.CharField("Product Color", max_length=50, null=False)

    def __str__(self):
        return "{color_id}-->{prod_color}".format(color_id=self.color_id,
                                                  prod_color=self.prod_color)


class PaperChoice(models.Model):
    paper_id = models.AutoField("Paper Choice ID", primary_key=True, auto_created=True)
    paper_choices_name = models.CharField("Paper Choices", max_length=50, null=False)

    def __str__(self):
        return "{}-->{}".format(self.paper_id,
                                self.paper_choices_name)


class SizeProductMapping(models.Model):
    size_p_map_id = models.AutoField("Size & Product Map ID", primary_key=True, auto_created=True)
    size_id = models.ForeignKey(Size, null=False, on_delete=models.CASCADE, verbose_name="Size ID")
    prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id")



class ColorProductMapping(models.Model):
    color_p_map_id = models.AutoField("Color & Product Map ID", primary_key=True, auto_created=True)
    color_id = models.ForeignKey(Color, null=False, on_delete=models.CASCADE, verbose_name="Color ID")
    prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id")


class PaperChoiceProductMapping(models.Model):
    paper_p_map_id = models.AutoField("Paper Choices & Product Map ID", primary_key=True, auto_created=True)
    paper_id = models.ForeignKey(PaperChoice, null=False, on_delete=models.CASCADE, verbose_name="Paper ID")
    prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id")

这是我的views.py,它不完整,我想使用这个将forms数据存储在model中
看法。 视图.py

#here in thi view method I am only getting data from models but not getting template data to store in the the model,
# I know I haven't taken inputs from the form here 
# I haven't done because I don't know what logic I should use here.
def order(request, id):
    products = Product.objects.all()
    sizesList = []
    ColorsList = []
    PaperChoiceProductsList = []    

    try:
        sizesMap = SizeProductMapping.objects.filter(prod_id=id)
        sizesList = [data.size_id.prod_size for data in sizesMap]
    except AttributeError:
        pass

    try:
        colorMap = ColorProductMapping.objects.filter(prod_id=id)
        ColorsList = [data.color_id.prod_color for data in colorMap]
    except AttributeError:
        pass

    try:
        PaperChoiceProductMap = PaperChoiceProductMapping.objects.filter(prod_id=id)
        PaperChoiceProductsList = [data.paper_id.paper_choices_name for data in PaperChoiceProductMap]
    except AttributeError:
        pass

    context = {'products': products,
               'sizesList': sizesList,
               "ColorsList": ColorsList,
               "PaperChoiceProductsList": PaperChoiceProductsList,
               }

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

订购。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">
                          
    <!-- The data I want to store in JSON starts from here -->
                            {% if sizesList %}
                            <div class="form-group">
                                <div class="form-group row mx-2">
                                    <label for="sizeList"
                                           class="form-control-label font-weight-bold card-header col-4 ml-4"
                                           style="background-color:#e3e4e6"><h5>Sizes : </h5></label>
                                    <div id="sizeList">
                                        {% for s in sizesList %}
                                        <input id="{{s}}" class="mx-2 my-auto" type="radio" name="size">
                                        <label for="{{s}}">{{s}}</label><br>
                                        {% endfor %}
                                    </div>
                                </div>
                            </div>
                            {% endif %}

                            {% if ColorsList %}
                            <div class="form-group">
                                <div class="form-group row mx-2">
                                    <label for="ColorsList"
                                           class="form-control-label font-weight-bold card-header col-4 ml-4"
                                           style="background-color:#e3e4e6"><h5>Colors : </h5></label>
                                    <div id="ColorsList">
                                        {% for c in ColorsList %}
                                        <input id="{{c}}" class="mx-2 my-auto" type="radio" name="Color">
                                        <label for="{{c}}">{{c}}</label><br>
                                        {% endfor %}
                                    </div>
                                </div>
                            </div>
                            {% endif %}

                            {% if PaperChoiceProductsList %}
                            <div class="form-group">
                                <div class="form-group row mx-2">
                                    <label for="ColorsList"
                                           class="form-control-label font-weight-bold card-header col-4 ml-4"
                                           style="background-color:#e3e4e6"><h5>Paper Choice : </h5></label>
                                    <div id="PaperChoiceProductsList">
                                        {% for pc in PaperChoiceProductsList %}
                                        <input id="{{pc}}" class="mx-2 my-auto" type="radio" name="PaperChoice">
                                        <label for="{{pc}}">{{pc}}</label><br>
                                        {% endfor %}
                                    </div>
                                </div>
                            </div>
                            {% endif %}

 <!-- The Data I want to store in the JSON ends here -->
                         
                            </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 %}

如上面模板注释中所述,我想将该数据存储在单个 JSON 中。

你能帮我为它创建一个视图吗?

网址.py

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

我使用 jason dump 方法将值存储在单个 json object 中,然后将其传递给该字段,它对我有用。

视图.py

import json

def order(request, id):
    products = Product.objects.all()
    sizesList = []
    ColorsList = []
    PaperChoiceProductsList = []
    value = {}
    try:
        sizesMap = SizeProductMapping.objects.filter(prod_id=id)
        sizesList = [data.size_id.prod_size for data in sizesMap]
    except AttributeError:
        pass

    try:
        colorMap = ColorProductMapping.objects.filter(prod_id=id)
        ColorsList = [data.color_id.prod_color for data in colorMap]
    except AttributeError:
        pass

    try:
        PaperChoiceProductMap = PaperChoiceProductMapping.objects.filter(prod_id=id)
        PaperChoiceProductsList = [data.paper_id.paper_choices_name for data in PaperChoiceProductMap]
    except AttributeError:
        pass
    if request.method == 'POST':
    if request.method == 'POST':
        customer_id = request.user
        product = Product.objects.get(prod_ID=id)
        product_id = product
        try:
            quantity = request.POST['quantity']
            print(quantity)
        except MultiValueDictKeyError:
            pass

        try:
            size = request.POST['size']
            value.update(size=size)
        except MultiValueDictKeyError:
            pass

        try:
            Colour = request.POST['Color']
            value.update(Colour=Colour)
        except MultiValueDictKeyError:
            pass

        try:
            Paper_Choice = request.POST['PaperChoice']
            value.update(Paper_Choice=Paper_Choice)
        except MultiValueDictKeyError:
            pass
        attribute_value = json.dumps(value)

        order_store = Order(user_id=customer_id, prod_id=product_id, quantity=quantity, attribute_value=attribute_value,
                            order_job_title=Job_title, order_desc=Order_Detail, address=User_Address, state=State,
                            city=City, postal_code=Postal_Code, product_img=TemplateValue)
        order_store.save()

    context = {'products': products,
               'sizesList': sizesList,
               "AqutousCoatingProductList": AqutousCoatingProductList,
               "ColorsList": ColorsList,
               "PaperChoiceProductsList": PaperChoiceProductsList,
               }
    return render(request, 'user/order.html', context)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM