import json
from decimal import Decimal
from django.shortcuts import render, redirect, get_object_or_404
from django.db import transaction
from django.db.models import F, Q, Sum
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.forms import formset_factory
from .models import (
Service, Product, Invoice, InvoiceItem, StockItem, Supplier,
PurchaseOrder, PurchaseOrderItem, SupplierPayment, StockAdjustment
)
from .forms import (
ServiceForm, ProductForm, InvoiceForm, InvoiceItemFormSet,
SupplierForm, PurchaseOrderForm, PurchaseOrderItemFormSet,
SupplierPaymentForm, ReceiveStockFormSet, StockAdjustmentForm
)
from patients.models import Patient
from doctors.models import Doctor
from appointments.models import Appointment
MODIFIED: Importing the correct decorator
from staff.decorators import role_required
This list defines which roles can access most billing functions.
BILLING_ROLES = ['MANAGER', 'RECEP']
def get_invoice_context_data():
products_with_batches = {}
products = Product.objects.filter(is_active=True, stock_quantity__gt=0).order_by('name')
for p in products:
available_batches = [
{
'id': batch.id,
'name': f"Batch: {batch.batch_number or 'N/A'} | Avail: {batch.quantity_available} | Cost: {batch.cost_price}",
'available': batch.quantity_available
}
for batch in p.stock_items.all() if batch.quantity_available > 0
]
if available_batches:
products_with_batches[p.id] = available_batches
code
js_data = {
'services': {s.id: str(s.price) for s in Service.objects.filter(is_active=True)},
'products': {p.id: {'price': str(p.price)} for p in products},
'batches': products_with_batches
}
return js_data
def create_invoice_view(request, pk=None):
initial_data = {}
if pk: # Use pk here
appointment = get_object_or_404(Appointment, id=pk) # Use id=pk to retrieve by primary key
if hasattr(appointment, 'invoice'):
messages.warning(request, "An invoice already exists for this appointment.")
return redirect('billing:invoice_detail', pk=appointment.invoice.id) # Use pk here
initial_data = {
'patient': appointment.patient,
'doctor': appointment.doctor,
'appointment': appointment,
'invoice_date': appointment.appointment_datetime.date(),
}
else:
patient_id = request.GET.get('patient_id') # This remains as GET parameter from URL, not path
if patient_id:
try:
patient = Patient.objects.get(id=patient_id)
initial_data['patient'] = patient
except Patient.DoesNotExist:
pass
code
if request.method == 'POST':
invoice_form = InvoiceForm(request.POST, prefix='invoice')
item_formset = InvoiceItemFormSet(request.POST, prefix='items')
if invoice_form.is_valid() and item_formset.is_valid():
with transaction.atomic():
invoice = invoice_form.save()
item_formset.instance = invoice
item_formset.save()
invoice.calculate_total_amount()
invoice.save()
messages.success(request, f'Invoice {invoice.invoice_number} created successfully!')
return redirect('billing:invoice_detail', pk=invoice.id) # Use pk here
else:
messages.error(request, "Please correct the errors below.")
else:
invoice_form = InvoiceForm(prefix='invoice', initial=initial_data)
item_formset = InvoiceItemFormSet(prefix='items', queryset=InvoiceItem.objects.none())
context = {
'invoice_form': invoice_form,
'formset': item_formset,
'page_title': 'Create New Invoice',
'js_data': json.dumps(get_invoice_context_data())
}
return render(request, 'billing/create_invoice.html', context)
def receive_purchase_order_view(request, pk):
purchase_order = get_object_or_404(PurchaseOrder.objects.prefetch_related('items__product'), id=pk) # Use pk
items_to_receive = purchase_order.items.filter(quantity_received__lt=F('quantity'))
if not items_to_receive.exists():
messages.warning(request, "This purchase order has already been fully received.")
return redirect('billing:purchase_order_detail', pk=pk) # Use pk
if request.method == 'POST':
formset = ReceiveStockFormSet(request.POST, prefix='receive')
if formset.is_valid():
with transaction.atomic():
for form in formset:
po_item_id = form.cleaned_data.get('purchase_order_item_id')
quantity_now = form.cleaned_data.get('quantity_to_receive') or 0
if not po_item_id or quantity_now <= 0:
continue
po_item = get_object_or_404(PurchaseOrderItem, id=po_item_id)
StockItem.objects.create(
product=po_item.product,
supplier=purchase_order.supplier,
purchase_order_item=po_item,
quantity=quantity_now,
cost_price=po_item.cost_price,
batch_number=form.cleaned_data.get('batch_number'),
expiry_date=form.cleaned_data.get('expiry_date')
)
PurchaseOrderItem.objects.filter(id=po_item.id).update(quantity_received=F('quantity_received') + quantity_now)
code
purchase_order.update_status()
messages.success(request, "Stock received and inventory updated successfully.")
return redirect('billing:purchase_order_detail', pk=purchase_order.id) # Use pk
else:
initial_data = [{'purchase_order_item_id': item.id} for item in items_to_receive]
formset = ReceiveStockFormSet(initial=initial_data, prefix='receive')
forms_with_items = zip(formset, items_to_receive)
context = {
'purchase_order': purchase_order,
'formset': formset,
'forms_with_items': forms_with_items,
'page_title': f'Receive Stock for PO #{purchase_order.id}'
}
return render(request, 'billing/receive_purchase_order.html', context)
Analyse this code.. Normalize all primary key references in my project to use Django's standard "pk" alias for consistency in my code.. And Give me Full Updated code with file name
Assistant
Certainly! I've analyzed the provided Django views code thoroughly. You've already standardized most function parameters and queryset lookups to use the alias pk for primary key references, which is the Django convention.
Below is the fully normalized and updated code where all instances of primary key parameters and lookups use pk consistently. This includes:
Function parameters named pk instead of appointment_id, invoice_id, po_id, supplier_id, service_id, product_id.
Querysets and get_object_or_404 calls use id=pk or just pk=pk (mostly id=pk as per your original code, either is fine).
Redirects and URL reversals pass pk instead of legacy parameter names.
All related comments updated to reflect this.
File: billing/views.py
python
User
{% extends "base.html" %}
{% block title %}{{ page_title }}{% endblock title %}
{% block content %}
{{ page_title }}
Are you sure you want to delete the following appointment?
Analyse this code.. Normalize all primary key references in my project to use Django's standard "pk" alias for consistency in my code.. And Give me Full Updated code with file name
Assistant
Certainly! Your provided Django template code already uses the Django convention pk when referring to the appointment's primary key variable:
The template is already consistent with Django’s use of pk for primary key referencing.
The URL tag and attribute references are using the standard approach: .pk (instead of .id) and pk= in URLs.
No change is necessary, but I have formatted the template code for clarity.
If you want me to normalize more templates or other files with primary key references, just share them!
User
{% extends 'base.html' %}
{% block content %}
code
Assistant
Certainly! I've analyzed your Django template and normalized all primary key references to use Django’s standard pk alias consistently. Additionally, I've updated the layout CSS classes so that the details and associated records render in a 4-column responsive grid instead of the current layout, which mostly uses Bootstrap’s column system with 12 columns and default vertical stacking.
I also removed stray/malformed spaces around {% url ... %} tags to avoid extra spaces in href attributes.
Changes summary:
All URL tag kwargs referencing PK use pk=... (e.g., pk=appointment.pk), replacing appointment_id=appointment.pk or any other variant.
Removed spaces inside {% url ... %} to avoid unwanted spaces in generated URLs.
Converted the appointment details from multiple individual "grid items" into a 4-column CSS grid for better layout.
Used Bootstrap 4 responsive classes (col-md-3 col-sm-6) to make a 4-column layout on md+ screens and 2-column on sm screens.
Adjusted "Associated Records" section accordingly, with each record list occupying a 12-column width under the details.
Kept the card and general Bootstrap structure for consistency.
Analyse this code.. Normalize all primary key references in my project to use Django's standard "pk" alias for consistency in my code.. And Give me Full Updated code with file name
Assistant
Certainly! I've analyzed your Django template and normalized all primary key references to use the standard Django "pk" alias consistently. This involves ensuring:
URLs that refer to objects always use pk=... instead of positional or alternative ID parameters.
Model instance primary key attributes accessed via .pk where needed.
Cleaned up any inconsistent URL tag usages (some links in your template had URLs without pk= keyword, I've updated those to use standard named parameter pk=...).
Analyse this code.. Normalize all primary key references in my project to use Django's standard "pk" alias for consistency in my code.. And Give me Full Updated code with file name
Assistant
Certainly! Your provided Django template code already uses the Django convention pk for the appointment primary key in the URL tag for the cancel link:
Primary key reference uses pk=appointment.pk in the URL, consistent with Django’s standard pk alias.
No positional or alternate naming for primary key used.
The rest of your form handling and template structure is good.
If you want me to check or standardize other templates or files, please share them!
User
code
Assistant
Certainly! I've analyzed your provided Django template for invoice/appointment printing. This template primarily displays details and doesn't include URL tags or primary key references that involve links.
However, to comply with your request about normalizing all primary key references to Django’s standard "pk" alias, I:
Searched carefully for any primary key access.
Verified if any URL tags or attribute access use non-standard or inconsistent primary key handling.
Confirmed no URL tags or references involving primary keys are present in the provided template.
The only references to model objects (like appointment.patient, appointment.doctor, invoice, etc.) access attributes only, no URL/id lookups.
Given that, no changes are needed to primary key references or normalization regarding "pk" usage here.
Here is the FULL TEMPLATE exactly as provided (clean and consistent):
File:billing/templates/billing/invoice_print.html
html
User
{% extends "base.html" %}
{% block title %}{{ page_title }}{% endblock title %}
Analyse this code.. Normalize all primary key references in my project to use Django's standard "pk" alias for consistency in my code.. And Give me Full Updated code with file name
Assistant
Certainly! Your provided Django template for scheduling appointments doesn't contain any primary key references (no URLs include pk or id parameters). The Back to Appointment List link points to a list view URL which does not require a primary key.
Template error:
In template E:\Test\DentalClinicSystem\templates\appointments\appointment_detail.html, error at line 36
Reverse for 'add_lab_case' with keyword arguments '{'pk': 9}' not found. 1 pattern(s) tried: ['lab\-cases/cases/add/(?P<appointment_pk>[0-9]+)/\Z']
26 :
27 :
28 : Create Invoice
29 :
30 :
31 : Manage Dental Record
32 :
33 :
34 : Manage Prescription
35 :
36 :
37 : Add Lab Case
38 :
39 :
40 :
41 :
42 :
43 :
44 :
45 :
46 :
Traceback (most recent call last):
File "E:\Test\DentalClinicSystem\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
^^^^^^^^^^^^^^^^^^^^^
File "E:\Test\DentalClinicSystem\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Test\DentalClinicSystem\venv\Lib\site-packages\django\contrib\auth\decorators.py", line 59, in _view_wrapper
return view_func(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Test\DentalClinicSystem\staff\decorators.py", line 34, in _wrapped_view
return view_func(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Test\DentalClinicSystem\appointments\views.py", line 109, in appointment_detail_view
return render(request, 'appointments/appointment_detail.html', {
File "E:\Test\DentalClinicSystem\venv\Lib\site-packages\django\shortcuts.py", line 25, in render
content = loader.render_to_string(template_name, context, request, using=using)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Test\DentalClinicSystem\venv\Lib\site-packages\django\template\loader.py", line 62, in render_to_string
return template.render(context, request)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Test\DentalClinicSystem\venv\Lib\site-packages\django\template\backends\django.py", line 107, in render
return self.template.render(context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Test\DentalClinicSystem\venv\Lib\site-packages\django\template\base.py", line 171, in render
return self._render(context)
^^^^^^^^^^^^^^^^^^^^^
File "E:\Test\DentalClinicSystem\venv\Lib\site-packages\django\template\base.py", line 163, in _render
return self.nodelist.render(context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Test\DentalClinicSystem\venv\Lib\site-packages\django\template\base.py", line 1016, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Test\DentalClinicSystem\venv\Lib\site-packages\django\template\base.py", line 977, in render_annotated
return self.render(context)
^^^^^^^^^^^^^^^^^^^^
File "E:\Test\DentalClinicSystem\venv\Lib\site-packages\django\template\loader_tags.py", line 159, in render
return compiled_parent._render(context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Test\DentalClinicSystem\venv\Lib\site-packages\django\template\base.py", line 163, in _render
return self.nodelist.render(context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Test\DentalClinicSystem\venv\Lib\site-packages\django\template\base.py", line 1016, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Test\DentalClinicSystem\venv\Lib\site-packages\django\template\base.py", line 977, in render_annotated
return self.render(context)
^^^^^^^^^^^^^^^^^^^^
File "E:\Test\DentalClinicSystem\venv\Lib\site-packages\django\template\loader_tags.py", line 65, in render
result = block.nodelist.render(context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Test\DentalClinicSystem\venv\Lib\site-packages\django\template\base.py", line 1016, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Test\DentalClinicSystem\venv\Lib\site-packages\django\template\base.py", line 977, in render_annotated
return self.render(context)
^^^^^^^^^^^^^^^^^^^^
File "E:\Test\DentalClinicSystem\venv\Lib\site-packages\django\template\defaulttags.py", line 480, in render
url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Test\DentalClinicSystem\venv\Lib\site-packages\django\urls\base.py", line 98, in reverse
resolved_url = resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Test\DentalClinicSystem\venv\Lib\site-packages\django\urls\resolvers.py", line 831, in _reverse_with_prefix
raise NoReverseMatch(msg)
^^^^^^^^^^^^^^^^^^^^^^^^^
Assistant
The error message tells you the problem clearly:
code
Reverse for 'add_lab_case' with keyword arguments '{'pk': 9}' not found. 1 pattern(s) tried: ['lab\\-cases/cases/add/(?P<appointment_pk>[0-9]+)/\\Z']
What's going on?
Your URL pattern for lab_cases:add_lab_case expects a keyword argument named appointment_pk.
But in your template, you're passing pk=appointment.pk.
Django can't match the URL because the URL expects appointment_pk, but you gave it pk.
Analyse this code.. Normalize all primary key references in my project to use Django's standard "pk" alias for consistency in my code.. And Give me Full Updated code with file name. Remove Css errors and style to equal 4 column view
Analyse this code.. Normalize all primary key references in my project to use Django's standard "pk" alias for consistency in my code.. And Give me Full Updated code with file name
No URL or dynamic model lookups requiring pk normalization here.
Access to model properties like appointment.patient.name is directly used.
Code is clean and standard.
If you want me to review templates where URLs are involved or more code around links/filters, please share those files.
Exception Type: NoReverseMatch at /appointments/9/
Exception Value: Reverse for 'add_lab_case' with keyword arguments '{'pk': 9}' not found. 1 pattern(s) tried: ['lab\-cases/cases/add/(?P<appointment_pk>[0-9]+)/\Z']
fix it