Hello, I am building a hire system for my workplace and I have hit a bit of a snag. The system should take a users information and save it, and then items are added to the user, so for example Joe Bloggs wants to hire a microphone for talking sake, then I have a model called new_hire that accommodates the information for each hire.
Below is my model
STATUS_CHOICES = (
('current', 'Current'),
('returned', 'Returned'),
)
user_name = models.CharField(max_length=100, verbose_name='user name', null=True)
items = models.ManyToManyField(Hire_Items, related_name='hires', verbose_name='items')
date = models.DateField(default=datetime.datetime.today, verbose_name='date', null=True)
returned = models.BooleanField(default=False, verbose_name='returned',null=True)
charge_code = models.CharField(max_length=100, verbose_name='charge code', null=True)
authority = models.CharField(max_length=100, verbose_name='authority', null=True)
contact_address = models.CharField(max_length=100, verbose_name='contact address', null=True)
telephone_no = models.CharField(max_length=100, verbose_name='telephone number', null=True)
location = models.CharField(max_length=100, verbose_name='location', null=True)
date_out = models.DateField(default=datetime.datetime.today, verbose_name='date out',null=True)
date_in = models.DateField(default=datetime.datetime.today, verbose_name='date in', null=True)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='current', verbose_name='hire status')
additional_items = models.TextField(verbose_name='Additional Items', blank=True, null=True,
help_text='List any additional items not in the system')
def __str__(self):
return f"{self.user_name} - Hire #{self.id}
This is where things get a bit complicated. So I have two apps in my project, the original hire_app which does all the initial signup and gathers information about a hire, and a hire_total app, which is where the data from the hire is summed up and stored.
This is the view that I use for the hire form in my hire_app
def hire_form(request):
if request.method == "POST":
form = UserForm(request.POST)
if form.is_valid():
try:
with transaction.atomic():
# Save the hire form as a NewHire instance
new_hire_instance = form.save(commit=False)
new_hire_instance.save()
# Update item availability if needed
# new_hire_instance.item.available = False
# new_hire_instance.item.save()
messages.success(request, "Hire successfully recorded!")
return redirect('table') # Redirect to the list view
except Exception as e:
messages.error(request, f"Error saving hire: {str(e)}")
else:
form = UserForm()
return render(request, "hire_form.html", {"form": form})
and this is the view from my hire_total app that saves the hire to the database
def save_hire(request):
try:
user_name = request.POST.get('user_name')
if not user_name:
return JsonResponse({
'success': False,
'message': 'No customer name provided.'
})
print("Save hire called")
total = Hire_Total(request)
hire_items = total.get_all_items()
# Debug print
if not hire_items:
return JsonResponse({
'success': False,
'message': 'No items in the hire to save.'
})
print(f"Creating hire for user {user_name} with {hire_items.count()} items")
# Create new hire instance
new_hire_instance = new_hire.objects.create(
user_name=user_name,
status='current',
date_out=datetime.datetime.today(),
)
# Debug print
print(f"Created new hire with ID: {new_hire_instance.id}")
# Add items to the many-to-many relationship
for item in hire_items:
new_hire_instance.items.add(item)
print(f"Added item {item.id} to hire {new_hire_instance.id}")
# Verify items were added
print(f"Items in hire after adding: {list(new_hire_instance.items.all())}")
# Clear the hire total
total.clear()
return JsonResponse({
'success': True,
'message': 'Hire saved successfully',
#'hire_id': new_hire_instance.id
})
except Exception as e:
print(f"Error in save_hire: {str(e)}")
return JsonResponse({
'success': False,
'message': f'Error saving hire: {str(e)}'
})
As you can see I have been trying to solve the issue through printing where the user name is associated with the hires to see if there is anything obvious with my code, but I’m stumped at this point. The system almost works the way I need it to, but whenever I save a hire with items, it saves one instance with all the hire information but no items, and one with just a name and the items that have been hired. I suspect I have made a simple error and any help would be greatly appreciated.