Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Python Could you help me fix my django forms code , I'm trying to get return_items based on the items_issued to a particular person

yrenhke

New Coder
here are my models
class IssueItem(models.Model):
id = models.BigAutoField(primary_key=True)
person = models.ForeignKey(Person, on_delete=models.CASCADE)
grouped_item = models.ForeignKey(
GroupedItems,
on_delete=models.CASCADE,
related_name=‘issue_items’
)
units_issued = models.DecimalField(max_digits=7, decimal_places=2, default=0)
Date = models.DateField(default=timezone.now)


def save(self, *args, **kwargs):
self.grouped_item.calculate_totals()
super().save(*args, **kwargs)

class return_item(models.Model):
id = models.BigAutoField(primary_key=True)
person = models.ForeignKey(Person,
on_delete=models.CASCADE
)
grouped_item = models.ForeignKey(
GroupedItems,
on_delete=models.CASCADE,
related_name=‘returned_items’
)
units_returned = models.DecimalField(max_digits=7, decimal_places=2, default=0)
Date = models.DateField(default=timezone.now)


def save(self, *args, **kwargs):
self.grouped_item.calculate_total()
super().save(*args, **kwargs)

def str(self):
return self.Person

class GroupedItems(models.Model):
id = models.BigAutoField(primary_key=True)
grouped_item = models.CharField(max_length=30, unique=True)
total_units = models.DecimalField(max_digits=9, decimal_places=2, default=0)
total = models.PositiveIntegerField(default=0)
units_used = models.DecimalField(max_digits=8, decimal_places=2, default=0)
units_available = models.DecimalField(max_digits=8, decimal_places=2, default=0)
Units_returned = models.DecimalField(max_digits=8, decimal_places=2, default=0)


def calculate_total(self):

return_items = self.returned_items.all()
self.Units_returned = return_items.aggregate(units_returned=Sum('units_returned'))['units_returned'] or 0
self.units_used = self.units_used - self.Units_returned
def calculate_totals(self):
issue_items = self.issue_items.all()


self.units_used = issue_items.aggregate(units_issued=Sum('units_issued'))['units_issued'] or 0


self.units_used = self.units_used - self.Units_returned
self.units_available = self.total_units - self.units_used

def function(self):
sqlserverconn_aggregate = sqlserverconn.objects.filter(grouped_item=self).aggregate(
total_units=Sum('Units'),
total=Sum(F('Unit_cost') * F('Units'))
)
self.total_units = sqlserverconn_aggregate['total_units'] or 0
self.total = sqlserverconn_aggregate['total'] or 0


def str(self):
return f"{self.grouped_item}"

def save(self, *args, **kwargs):

super().save(*args, **kwargs)

class Meta:
indexes = [
models.Index(fields=['grouped_item', 'total_units'], name='grouped_item_total_units_idx'),
]

class Person(models.Model):
person = models.CharField(max_length=20)


def str(self):
return self.person

i have recievers to handle calculations don’t worry , where i am getting a problem is iin my forms specifically return_item form
class ReturnItemForm(forms.ModelForm):
person = forms.ModelChoiceField(
queryset=Person.objects.all(),
widget=forms.Select(attrs={‘class’: ‘form-control’}),
empty_label=None,
to_field_name=‘id’
)
Date = forms.DateField(
widget=forms.DateInput(attrs={‘class’: ‘form-control’, ‘type’: ‘date’}),
initial=timezone.now()
)
grouped_item = forms.ModelChoiceField(
queryset=IssueItem.objects.all().values_list(‘grouped_item__grouped_item’, flat=True).distinct(),
widget=forms.Select(attrs={‘id’: ‘id_grouped_item’}),
to_field_name=‘grouped_item’
)


class Meta:
model = return_item
fields = ['person', 'grouped_item', 'units_returned', 'Date']

def init(self, *args, **kwargs):
super(ReturnItemForm, self).init(*args, **kwargs)
if 'person' in self.data:

selected_person = self.data['person']

self.fields['grouped_item'].queryset = IssueItem.objects.filter(person=selected_person)

def clean_units_issued(self):
units_returned = self.cleaned_data.get('units_returned')
grouped_item = self.cleaned_data.get('grouped_item')

if units_returned > grouped_item.units_issued:
raise forms.ValidationError('units_returned', 'Units returned cannot exceed units issued.')

return units_returned

it when i input a person and the grouped items i get this error

ValueError at /return_item/​

Cannot assign “<IssueItem: IssueItem object (3)>”: “return_item.grouped_item” must be a “GroupedItems” instance.
i just want it to know that the item that is being selected was from a specific user if there is a way you can help me thanks
 
It seems like the issue is in the way you're populating the grouped_item field in your ReturnItemForm. The field is expecting a GroupedItems instance, but you are currently providing a queryset of IssueItem instances.

To fix this, you should modify the ReturnItemForm to properly filter the available grouped items based on the selected person. Here's a modified version of your ReturnItemForm:




Python:
from django import forms
from .models import return_item, Person, IssueItem

class ReturnItemForm(forms.ModelForm):
    person = forms.ModelChoiceField(
        queryset=Person.objects.all(),
        widget=forms.Select(attrs={'class': 'form-control'}),
        empty_label=None,
        to_field_name='id'
    )
    
    Date = forms.DateField(
        widget=forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}),
        initial=timezone.now()
    )
    
    grouped_item = forms.ModelChoiceField(
        queryset=GroupedItems.objects.all(),
        widget=forms.Select(attrs={'id': 'id_grouped_item'}),
        to_field_name='grouped_item'
    )

    class Meta:
        model = return_item
        fields = ['person', 'grouped_item', 'units_returned', 'Date']

    def __init__(self, *args, **kwargs):
        super(ReturnItemForm, self).__init__(*args, **kwargs)
        if 'person' in self.data:
            selected_person = self.data['person']
            self.fields['grouped_item'].queryset = IssueItem.objects.filter(person=selected_person).values_list('grouped_item', flat=True).distinct()

    def clean_units_returned(self):
        units_returned = self.cleaned_data.get('units_returned')
        grouped_item = self.cleaned_data.get('grouped_item')

        if units_returned > grouped_item.units_issued:
            raise forms.ValidationError('Units returned cannot exceed units issued.')

        return units_returned



In this modified version:

  1. The grouped_item field queryset is set to GroupedItems.objects.all() to allow the user to choose from all available grouped items.
  2. In the init method, the queryset for grouped_item is filtered based on the selected person.
Make sure that you have imported GroupedItems at the beginning of your forms.py file:

Python:
from .models import return_item, Person, IssueItem, GroupedItems


This should resolve the error you're encountering.


Anyone Can Learn to Code! 550+ Hours of course content!
 

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom