Form input data in multiple table rows at the same time

I am trying to insert data into a table using django form but when i try to save the values i keep getting an error that the object has no attribute “…”
forms.py

class inflowForm(forms.ModelForm):
    class Meta:
        model = poItem
        fields = ['expiryDate', 'added_quantity']

    expiryDate =  forms.DateField(
        widget=DateInput
        )

views.py

def inflowA2(request, pk):
    page = "inflowA2"

    employee = Employee.objects.get(uuid = request.user.uuid)

    today = date.today()

    orderNo = po.objects.get(number = pk)

    orderItems = poItem.objects.filter(po__number = pk)

    today = date.today()

    form = inflowForm()

    if request.method == "POST":
        form= inflowForm(request.POST)
        if form.is_valid():
            form.save(commit=False)
            for x in orderItems:
                if x.item.category == "مُجْمِعٌ":
                    form.expiryDate = x.item.expiryDate
                form.added_quantity += x.item.quantity
                form.save()
            # return HttpResponseRedirect (reverse ("inflowA2", args=[request.POST['number']]))

    context = {
        'page': page,
        'employee': employee,
        'date': today,
        'po': orderNo,
        'items':orderItems,
        'form': form
        }
    
    return render(request, "forms/warehouse/inflow/a2.html", context)

models.py

class po(models.Model):
    uuid = models.UUIDField(primary_key=True,default=uuid.uuid4, editable=False, max_length=36)
    number = models.IntegerField(auto_created=True)
    employee = models.ForeignKey(Employee, on_delete=models.CASCADE)
    supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
    warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE)
    completed = models.BooleanField(default=False)
    po_created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.uuid)

class poItem(models.Model):
    uuid = models.UUIDField(primary_key=True,default=uuid.uuid4, editable=False, max_length=36)
    item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='items')
    po = models.ForeignKey(po, on_delete=models.CASCADE, related_name='poitems')
    required_quantity = models.IntegerField()
    added_quantity = models.IntegerField()
    expiryDate = models.DateField(null=True, blank=True)

    class Meta:
        ordering = ('item',)

    def __repr__(self):
        return self.item.description

class Item(models.Model):
    uuid = models.UUIDField(primary_key=True,default=uuid.uuid4, editable=False, max_length=36)
    # name = models.CharField(max_length=100)
    description = models.TextField()
    expiryDate = models.DateField(null=True, blank=True)
    quantity = models.IntegerField()
    category_choices = (
    ('مستوي واحد','مستوي واحد'),
    ('مُجْمِعٌ','مُجْمِعٌ'),
    )
    category = models.CharField(
        max_length=15,
        choices=category_choices
    )
    unit_choices = (
    ('صندوق','صندوق'),
    ('متر','متر'),
    ('عدد','عدد'),
    )
    unit = models.CharField(
        max_length=15,
        choices=unit_choices
    )

    def __str__(self):
        return self.description

html file

 <form action="{% url "inflowA2" po.number %}" method="post">
                    {% csrf_token %}
                            <tbody>
                                {% for x in items %}
                                    <tr class="table-text position">
                                        <td>{{x.item.description}}</td>
                                        <td>{{x.item.category}}</td>
                                        {% if x.item.category == "مُجْمِعٌ" %}
                                            <td>{{form.expiryDate}}</td>
                                        {% else %}
                                            <td>-</td>
                                        {% endif %}
                                        <td>{{x.item.unit}}</td>
                                        <td>{{x.required_quantity}}</td>
                                        <td>{{x.item.quantity}}</td>
                                        <td>{{form.added_quantity}}</td>
                                    </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                        
                    </div>  
                    
                    <div>
                        <button class="button button-search">تأكيد</button>
                    </div>
                </form>


Hi there, the error is coming from line 110 of the view.py, I think you need to do this instead:

     for x in orderItems.all(): # add this instead to retrieve all the objects in your poItem 
            if x.item.category == "مُجْمِعٌ":
                form.expiryDate = x.item.expiryDate
               form.added_quantity += x.item.quantity

# your other codes

still getting the same error

AttributeError at /PO-Detail/1/
'inflowForm' object has no attribute 'added_quantity'
Request Method:	POST
Request URL:	http://127.0.0.1:8001/PO-Detail/1/
Django Version:	4.1.7
Exception Type:	AttributeError
Exception Value:	
'inflowForm' object has no attribute 'added_quantity'
Exception Location:	/app/users/views.py, line 110, in inflowA2
Raised during:	users.views.inflowA2
Python Executable:	/usr/local/bin/python
Python Version:	3.9.18
Python Path:	
['/app',
 '/usr/local/lib/python39.zip',
 '/usr/local/lib/python3.9',
 '/usr/local/lib/python3.9/lib-dynload',
 '/usr/local/lib/python3.9/site-packages']
Server time:	Mon, 16 Oct 2023 16:41:54 +0300

views.py

def inflowA2(request, pk):
    page = "inflowA2"

    employee = Employee.objects.get(uuid = request.user.uuid)

    today = date.today()

    orderNo = po.objects.get(number = pk)

    orderItems = poItem.objects.filter(po__number = pk)

    today = date.today()

    form = inflowForm()

    if request.method == "POST":
        form= inflowForm(request.POST)
        if form.is_valid():
            form.save(commit=False)
            for x in orderItems.all():
                if x.item.category == "مُجْمِعٌ":
                    form.expiryDate = x.item.expiryDate
                form.added_quantity += x.item.quantity
                form.save()
            return HttpResponseRedirect (reverse ("homePage"))

    context = {
        'page': page,
        'employee': employee,
        'date': today,
        'po': orderNo,
        'items':orderItems,
        'form': form
        }
    
    return render(request, "forms/warehouse/inflow/a2.html", context)

froms.py

class inflowForm(forms.ModelForm):
    class Meta:
        model = poItem
        fields = ['expiryDate', 'added_quantity']

    expiryDate =  forms.DateField(
        widget=DateInput()
        )
    
    added_quantity = forms.IntegerField(
        widget= forms.NumberInput()
    )

i tried to comment form.added_quantity then i started getting this error.

IntegrityError at /PO-Detail/1/
null value in column "required_quantity" of relation "purchase_poitem" violates not-null constraint
DETAIL:  Failing row contains (09bddd11-eb20-47ed-95e5-71f93c03065c, null, 100, 2023-11-01, null, null).
Request Method:	POST
Request URL:	http://127.0.0.1:8001/PO-Detail/1/
Django Version:	4.1.7
Exception Type:	IntegrityError
Exception Value:	
null value in column "required_quantity" of relation "purchase_poitem" violates not-null constraint
DETAIL:  Failing row contains (09bddd11-eb20-47ed-95e5-71f93c03065c, null, 100, 2023-11-01, null, null).
Exception Location:	/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py, line 89, in _execute
Raised during:	users.views.inflowA2
Python Executable:	/usr/local/bin/python
Python Version:	3.9.18
Python Path:	
['/app',
 '/usr/local/lib/python39.zip',
 '/usr/local/lib/python3.9',
 '/usr/local/lib/python3.9/lib-dynload',
 '/usr/local/lib/python3.9/site-packages']
Server time:	Mon, 16 Oct 2023 16:45:17 +0300

I got the required quantity to work by doing the following but now i keep getting this error

ValueError at /PO-Detail/1/
Cannot assign "UUID('7a3cf20e-1804-4cc3-a04b-4b3069cf5222')": "poItem.item" must be a "Item" instance.
Request Method:	POST
Request URL:	http://127.0.0.1:8001/PO-Detail/1/
Django Version:	4.1.7
Exception Type:	ValueError
Exception Value:	
Cannot assign "UUID('7a3cf20e-1804-4cc3-a04b-4b3069cf5222')": "poItem.item" must be a "Item" instance.
Exception Location:	/usr/local/lib/python3.9/site-packages/django/db/models/fields/related_descriptors.py, line 237, in __set__
Raised during:	users.views.inflowA2
Python Executable:	/usr/local/bin/python
Python Version:	3.9.18
Python Path:	
['/app',
 '/usr/local/lib/python39.zip',
 '/usr/local/lib/python3.9',
 '/usr/local/lib/python3.9/lib-dynload',
 '/usr/local/lib/python3.9/site-packages']
Server time:	Mon, 16 Oct 2023 17:00:26 +0300
Traceback Switch to copy-and-paste view
/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py, line 56, in inner
                response = get_response(request) …
Local vars
/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py, line 197, in _get_response
                response = wrapped_callback(request, *callback_args, **callback_kwargs) …
Local vars
/app/users/views.py, line 111, in inflowA2
                items.item = x.item.uuid …
Local vars
/usr/local/lib/python3.9/site-packages/django/db/models/fields/related_descriptors.py, line 237, in __set__
            raise ValueError( …
Local vars

views.py

def inflowA2(request, pk):
    page = "inflowA2"

    employee = Employee.objects.get(uuid = request.user.uuid)

    today = date.today()

    orderNo = po.objects.get(number = pk)

    orderItems = orderNo.poitems.all()

    today = date.today()

    form = inflowForm()

    if request.method == "POST":
        form= inflowForm(request.POST)
        if form.is_valid():
            items = form.save(commit=False)
            for x in orderItems:
                items.required_quantity = x.required_quantity
                items.item = x.item.uuid
                items.po = po.objects.get(uuid = x.po.uuid)
                items.save()
            form = inflowForm()
            return HttpResponseRedirect (reverse ("homePage"))
        
    context = {
        'page': page,
        'employee': employee,
        'date': today,
        'po': orderNo,
        'items':orderItems,
        'form': form
        }
    
    return render(request, "forms/warehouse/inflow/a2.html", context)

The problem is that you’re accessing the wrong objects here.

The function call form.save(...) returns the instance of the model being saved. It’s that object that you want to make the subsequent modifications to, along with it being what you save after those changes.
example:

...
new_po_item = form.save(commit=False)
...
new_po_item.expiry_date = x.item.expiry_date
new_po_item.added_quantity += x.item.quantity
new_po_item.save()