I have two models in my django application 'Client' and 'Installment'. Below is my models.py:
models.py
rom django.db import models
from django.utils import timezone
from django.urls import reverse
# Create your models here.
class Client(models.Model):
name = models.CharField(max_length = 100)
dob = models.SlugField(max_length = 100)
CNIC = models.SlugField(max_length = 100)
property_type = models.CharField(max_length = 100)
down_payment = models.IntegerField()
date_posted = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('client_details',kwargs={ 'pk' : self.pk})
class Installment(models.Model):
client = models.ForeignKey(Client, null=True, on_delete=models.CASCADE)
installment_month = models.CharField(max_length = 100)
installment_amount = models.IntegerField()
installment_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.installment_month
def get_absolute_url(self):
return reverse('installment_confirmation')
and my views.py
view.py
# To create new client
class ClientCreateView(CreateView):
model = Client
fields = ['name', 'dob', 'CNIC', 'property_type', 'down_payment']
# To add new installment
class AddInstallmentView(CreateView):
model = Installment
#template_name = "property_details/addinstallment_form.html"
fields = ['installment_month', 'installment_amount']
And the URL that I have to add a new installment is below:
urlpatterns = [
path('', ClientListView.as_view(), name='client_list'),
path('new/', ClientCreateView.as_view(), name='add_client'),
path('<int:pk>/', ClientDetailView.as_view(), name='client_details'),
path('<int:pk>/Add-Installment', AddInstallmentView.as_view(), name='add_installment'),
path('confirmation/', views.installment_added, name='installment_confirmation'),
]
You can see that the URL for adding new installment is unique. For example,
/<local_server_addr>/<client.id>/Add-Installment (because of <int:pk> above)
I can create a new client and also I can add installment.
But how to connect an installment to a particular client?
How to use this client.id
as an owner of the current installment?
It looks like, when one client is created, it is being assigned with some ID from django. Now, how can I use that ID to link it to the installment that I am going to add?