简体   繁体   English

如何在字段中插入我的 django 模型数据以编辑记录

[英]How I can insert my django model data in fields for edit a record

I want to edit my product which all data is already in django model.我想编辑我的产品,所有数据都已经在 django 模型中。 When i add press the "edit" button in option a new form is open to edit a product but I don't know who to insert data in fields.当我添加按选项中的“编辑”按钮时,会打开一个新表单来编辑产品,但我不知道该向谁插入数据。 Kindly give me guidance how i display me data in fields there is the image of my product请给我指导我如何在字段中显示我的数据有我的产品图像

and that is edit form if you see before the edit button data is displaying but i want that data in form fields如果您在编辑按钮数据显示之前看到,那就是编辑表单,但我想要表单字段中的数据

views.py视图.py

class EditProduct(TemplateView):
    template_name = 'stock/editproduct.html'

    def get(self, request, product_id):
        productedit = get_object_or_404(Product, pk=product_id)
        form = EditProductForm()
        args = {'form':form, 'productedit':productedit}
        return render(request, self.template_name, args)

template.html模板.html

{% extends 'base.html' %}
{% block content %}
<div>
    <h4>Edit Product!</h4>
    <hr/>

  <form method="post" enctype="multipart/form-data" >
    {% csrf_token %}
    {{ form.as_p }}
    <h4>{{productedit.pro_name}}</h4>
    <p>{{productedit.companyName}}</p>
    <p>{{productedit.Sale_Price}}</p>
    <p>{{productedit.Quantity}}</p>
    <button type="submit" class="btn btn-success" >Edit</button>
  </form>
</div>
{% endblock %}

form.py表单.py

class EditProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = ('companyName', 'pro_name', 'Purchase_Price', 'Sale_Price', 'Quantity', 'Picture' )

    def __init__(self, *args, **kwargs):
        super(EditProductForm, self).__init__(*args, **kwargs)
        self.fields['companyName'].label    = 'Company Name'
        self.fields['pro_name'].label       = 'Product Name'
        self.fields['Purchase_Price'].label = 'Purchase Price'
        self.fields['Sale_Price'].label     = 'Sale Price'

you have to add an instance你必须添加一个实例

views.py视图.py

    def get(self, request, product_id):
        productedit = get_object_or_404(Product, pk=product_id)
        data=Product.objects.filter(id=product_id)
        form = EditProductForm(instance=data)
        args = {'form':form, 'productedit':productedit}
        return render(request, self.template_name, args)

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

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