简体   繁体   English

Django 用户如何从模板向 model 添加新属性

[英]Django how a user can add a new attribute to a model from template

I have the following model:我有以下 model:

models.py:模型.py:

class Product(models.Model):
name = models.CharField(blank=False, max_length=255)
description = models.TextField()


class Ingredients(models.Model):
    ingredients = models.ForeignKey(Product, related_name='ingredients', on_delete=models.CASCADE, null=True)
    salt = models.IntegerField(default=0)
    pepper = models.IntegerField(default=0)

views.py:视图.py:

def productdetails(request, product_pk):
product = get_object_or_404(Product, pk=product_pk)
ingredients = get_object_or_404(Ingredients, ingredients_id=product_pk)
salt = ingredients.salt
pepper = ingredients.pepper
if request.method == 'POST':
    form = IngredientsForm(request.POST)
    newvalue = form.save(commit=False)
    newvalue.user = request.user
    newvalue.save()
    return render(request, 'xxx.html', {'product': product, 'form': IngredientsForm, 'salt': salt, 'pepper': pepper})
return render(request, 'xxx.html', {'product': product, 'iform': IngredientsForm, 'salt': salt, 'pepper': pepper})

def updateproduct(request, product_pk):
    ingredients = get_object_or_404(Ingredients, ingredients_id=product_pk)
    form = IngredientsForm(request.POST or None, instance = ingredients)
    salt = ingredients.salt
    pepper = ingredients.pepper
    if form.is_valid():
        form.save()
        products = Product.objects.filter()
        return render(request, 'xxx.html', {'products': products})
    return render(request, 'xxx.html', {'form': form, 'salt': salt, 'pepper': pepper, 'product_pk': product_pk})

def createingredients(request, product_pk):
    if request.method == 'POST':
        ingredients = get_object_or_404(Ingredients, ingredients_id=product_pk)    
        form = IngredientsForm(request.POST or None, instance=ingredients
        salt = ingredients.salt
        pepper = ingredients.pepper
        # here should be the code
        return render(request, 'xxx.html', {'ingredients': ingredients, 'product_pk': product_pk})

In template:在模板中:

  <div class="container">
<strong>Ingredients:</strong>
<b>Salt: </b>{{ salt }} g <br>
<b>Pepper: </b>{{ pepper }} g <br>
<br>

  Update ingredients:
  {% if error %}
  <div class="alert alert-danger" role="alert">
      {{ error }}
  </div>
  {% endif %}
<form method="POST">
    {% csrf_token %}

    {{ form.as_p }}

    <input type="submit" value="Update">
</form>

<br>
Add ingredient:
<form action="{% url 'createingredients' product_pk %}" method="POST">
  {% csrf_token %}
  <br />
  <p>Name: <input type="text" name="ingredientname" /> Value: <input type="number" name="ingredientvalue" /> <input type="submit" value="Add"></p>
  <br />

</form>

What I try to achieve is that in the template the user should be able to add, delete, update and view Ingredients as he wish.我试图实现的是,在模板中,用户应该能够按照自己的意愿添加、删除、更新和查看成分。 For example, user can add the sugar ingredient of that product ( which is not defined in the ingredients models ) with the value of 150 and after that to delete the salt ingredient.例如,用户可以添加该产品的糖成分(未在成分模型中定义),值为 150,然后删除盐成分。 In this case the template will need to list only sugar and pepper ( as salt was deleted by user ) ingredients of that product and allow user to always change values or add/delete more ingredients of that product from the product detail page.在这种情况下,模板将只需要列出该产品的糖和胡椒(因为盐已被用户删除)成分,并允许用户始终更改值或从产品详细信息页面添加/删除该产品的更多成分。 The user should be allowed to add as many ingredients as he wants, no matter if those ingredients are not in the ingredients models.应该允许用户添加任意数量的成分,无论这些成分是否不在成分模型中。 Appreciate any help.感谢任何帮助。

What you want requires adding new columns in the ingredients table.您想要的需要在成分表中添加新列。 Theoretically you can achieve that, with some scripting and custom management commands and cron jobs, but it will require you to build an entire sub-system that does it.从理论上讲,您可以通过一些脚本和自定义管理命令以及 cron 作业来实现这一点,但这需要您构建一个完整的子系统来完成它。 Additionally allowing the user direct access to the database structure is not a practice you should consider in production ever.此外,允许用户直接访问数据库结构不是您在生产中应该考虑的做法。 What you need is to alter your database design-replace the definition of the ingredients record with a type/name, value, unit triplet, and instead of adding column add records.你需要改变你的数据库设计——用类型/名称、值、单位三元组替换成分记录的定义,而不是添加列添加记录。

class Ingredients(models.Model):
    class TYPE:
        SALT   = 0
        PEPPER = 1
        #add more here
   
     class UNIT:
        GRAM = 0
        KILOGRAM = 1
        LITER    = 2
        POUND    = 3
        #add more here
        
        # an optional unit conversion 
        # call using Ingredients.UNIT.convert(unit1,unit2,quantity)
        @staticmethod
        def convert(from, to, quantity):
           factor = 1
           #calculate conversion factor here
           ....

           return quantity * factor        

    ingredients = models.ForeignKey(Product, related_name = 'ingredients',
                                             on_delete    = models.CASCADE, null=True)
    #an Ingredients.TYPE member. For example Ingredients.TYPE.SALT
    type     = models.IntegerField(default=0)
    #an Ingredients.UNIT memeber. For example Ingrediens.UNIT.GRAM
    unit     = models.IntegerField(default=0)

    quantity = models.IntegerField(default=0)
    

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

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