Hi All,
My goal here is to create fill the database with many to one relationship. What I mean by this is for example, a hospital can have multiple doctors, so all the doctors which belongs to the same hospital will have the same hospital _id/name. So, this what I am trying to achieve. I am totally new to django. What I came across as a solution is to use modelset_factory. But I am not able to apply it
model.py
from django.db import models
class HospitalDataModel(models.Model):
hospital_name = models.CharField(max_length=50)
def __str__(self):
return f"Hospital Added: {self.hospital_name}"
class StaffDataModel(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
dept_name = models.CharField(max_length=50)
doctor_id = models.IntegerField()
username = models.CharField(max_length=15, null=True)
password = models.CharField(max_length=20, null=True)
# Since a single hospital can have multiple staff that is why one to many
hospital = models.ForeignKey(HospitalDataModel, on_delete=models.CASCADE)
def __str__(self):
return f"Doctor {self.first_name} {self.last_name}"
views.py
from django.shortcuts import render, redirect
from .forms import UserCreationForm
from django.contrib import messages
from .models import StaffDataModel, HospitalDataModel
from django.forms import modelformset_factory
def register(request, hospital_id):
hospital = HospitalDataModel.objects.get(pk=hospital_id)
staff_formset = modelformset_factory(StaffDataModel, form=UserCreationForm)
if request.method == "POST":
formset = staff_formset(request.POST, queryset=StaffDataModel.objects.filter(hospital_id=hospital.id),
)
# form = UserCreationForm(request.POST)
# print(form.errors)
if formset.is_valid():
instances = formset.save(commit=False)
for instance in instances:
instance.hospital_id = hospital.id
instance.save()
# # print(form.fields)
# username = form.cleaned_data.get('username')
# messages.success(request, f'User {username} Registered')
return redirect('app-workspace')
formset = staff_formset(queryset=StaffDataModel.objects.filter(hospital__id=hospital.id))
# form = UserCreationForm()
return render(request, 'users/register.html', {'form': formset})
forms.py
from django import forms
from random import randrange as rand_num
from .models import HospitalDataModel, StaffDataModel
class UserCreationForm(forms.ModelForm):
first_name = forms.CharField(label='First Name', max_length=100)
last_name = forms.CharField(label='Last Name', max_length=100)
username = forms.CharField(label='Username', max_length=100)
dept_name = forms.CharField(max_length=50, required=False)
doctor_id = forms.IntegerField(initial=str(rand_num(0,100)))
doctor_id.disabled = True
hospital = forms.CharField(label='Hospital', max_length=12, required=False)
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = StaffDataModel
fields = [ 'doctor_id', 'first_name', 'last_name', 'username', 'password']