简体   繁体   English

Django 一种形式的两种模型

[英]Django two models on one form

Thanks in advance.提前致谢。 This is my first question on StackOverflow.这是我关于 StackOverflow 的第一个问题。 I am a newbie to Django and I'm trying to create an inventory checklist for someone to quickly look at the inventory and place a number in the count column.我是 Django 的新手,我正在尝试为某人创建一个库存清单,以便快速查看库存并在计数列中放置一个数字。 What I am missing is how to link the count field to the item_name (iterate the count field with the item_name. When I type in values and submit it makes each count field equal to the first count field. Please see attachments of screenshots.我缺少的是如何将计数字段链接到 item_name (用 item_name 迭代计数字段。当我输入值并提交时,它会使每个计数字段等于第一个计数字段。请参阅截图的附件。

Here is my models.py这是我的models.py

class InventoryItem(models.Model):
    item_name = models.CharField(max_length=200, null=True)

class InventoryChecklist(models.Model):
    count = models.CharField(max_length=10, null=True)
    date_posted = models.DateTimeField(default=timezone.now)
    item = models.ForeignKey(InventoryItem, on_delete=models.CASCADE)

forms.py表格.py

class InventoryCheck(ModelForm):
    class Meta:
        model = InventoryChecklist
        fields = '__all__'

views.py视图.py

def DailyCount(request):
    items = InventoryItem.objects.all()
        
    form = InventoryCheck
    if request.method == 'POST':
        form = InventoryCheck(request.POST)

        if form.is_valid():
            form.save()

            return redirect('/')

    context = {'items':items, 'form':form}
    return render(request, 'checklist/dailycount.html', context)

template模板

<table class="table table-sm">
                <tr>
                    <th>Item Name</th>
                    <th>Count</th>
                    <th>Date</th>  
                </tr>
            <form action="" method='POST'>
                {% csrf_token %}

                    {% for item in items %}
                            
                    <tr>
                        <td>{{ item.item_name }}</td>
                        <td>{{ form.count }}</td>
                    </tr>
                    
                    {% endfor %}
                    <input type="submit" name="Save" /> 
            </form>

            </table>

rendered template before submit rendered template after submit提交前渲染模板 提交后渲染模板

form = InventoryCheck is passing in the class, but not an initialized object. form = InventoryCheck正在传递类,但不是已初始化的对象。 Your form is not really... iterable (ie when you're doing form.count )?你的表单不是真的......可迭代(即当你在做form.count )? Do you mean to do item.count ?你的意思是做item.count吗?

Edit: since you're grabbing all items, you should instead do:编辑:由于您要抓取所有物品,因此您应该执行以下操作:

items = InventoryChecklist.objects.all()

and then work off that.然后解决这个问题。 That way, in your template, you can do:这样,在您的模板中,您可以执行以下操作:

{{ item.item.item_name }}
{{ item.count }}

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

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