Search code examples
pythondjangodatabasemodel

Problem in making one to one relation in django


I am creating a website where admin will have the right to register the clinic/patient and fill his complete details wile registration

Below is my code

model.py

import django
from django.db import models
from django.contrib.auth.models import AbstractUser

class Registered_user(AbstractUser):
   is_clinic = models.BooleanField(default=False)
   is_patient = models.BooleanField(default=False)
   token =  models.CharField(max_length=120, default=None, null= True)
   forgot_token = models.CharField(default=None, max_length=120, null=True),
   email =  models.EmailField(unique = True, max_length=254, verbose_name='email address')
   
#clinic
class Clinic(models.Model):
   register_user =  models.OneToOneField(Registered_user, on_delete=models.CASCADE, primary_key=True,) 
   clnc_name = models.CharField(max_length=255)
   clnc_phone = models.BigIntegerField(null= True)
   clnc_contact_name = models.CharField(max_length=255)
   clnc_Job_Title = models.CharField(max_length=255)
   clnc_address_line1 = models.CharField(max_length=255)
   clnc_address_line2 = models.CharField(max_length=255)
   clnc_county = models.CharField(max_length=255)                                                          
   clnc_postcode = models.CharField(max_length=255)
   clnc_town_city = models.CharField(max_length=255)
   clnc_created_at = models.DateTimeField(auto_now_add=True)
   clnc_status = models.BooleanField(default=False)
   updated = models.DateTimeField(auto_now=True)
   published = models.DateTimeField(default=django.utils.timezone.now)

View.py

from django.shortcuts import render, redirect
from adminPanel.models import Registered_user
from adminPanel.models import Clinic

def create_clinic(request):
    """This function will handle the process of registering new clinic to the portal, where user can register with following attributes
        clinic_name, contact_name, Job_Title, address_line1, address_line2, county, postcode, town_city, clinic_email, clininc_phone
    Args:
        request: client to server request
    Returns:
        title: This will pass the title from backend to the html
    """
    title = 'Create Clinic'
    request_url = request.get_full_path()
    if request.method == "POST":
        domain_name=get_current_site(request).domain
        token=str(random.random()).split('.')[1]
        link=f'http://{domain_name}/resetpassword/{token}'
        clinic_name = request.POST.get('clinic_name')
        contact_name = request.POST.get('contact_name')
        Job_Title = request.POST.get('Job_Title')
        address_line1 = request.POST.get('address_line1')
        address_line2 = request.POST.get('address_line2')
        country = request.POST.get('country')
        postcode = request.POST.get('postcode')
        town_city = request.POST.get('town_city')
        clinic_email = request.POST.get('clinic_email')
        clinic_phone = request.POST.get('clinic_number')            clinic_user_instances = Registered_user.objects.create(
                username = clinic_user_name,
                email = clinic_email,
                token = token,
                is_clinic=True
            )
            clinic_user_instances.save()
            
            clinic_instances = Clinic.objects.create(
                clnc_name = clinic_name,
                clnc_phone = clinic_phone,
                clnc_contact_name = contact_name,
                clnc_Job_Title = Job_Title,
                clnc_address_line1 = address_line1,
                clnc_address_line2 = address_line2,
                clnc_county = country,
                clnc_postcode = postcode,
                # clnc_town_city =town_city,
                # username = clinic_username,
                # email = clinic_email,
                # token = token,
                # is_clinic=True
                
            )
            clinic_instances.save
            messages.info(request, f'{clinic_name} added successfully Please check your mail to set password')
            
            subject = 'Reset password'
            email_template = get_template('email.html').render({'link': link})
            from_email = '[email protected]'
            message = EmailMessage(subject, email_template, from_email, [clinic_email])
            message.content_subtype='html'
            message.send()
            
        else:
            content = {
                'title': title, 
                'requesturl':request_url,
                'clinic_values':clinic_values,
                'error': error
            }
            return render(request, 'create_clinic.html', content)
    return render(request, 'create_clinic.html', {'title': title, 'requesturl':request_url})

error null value in column "register_user_id" of relation "adminPanel_clinic" violates not-null constraint get null value

Please help

I have tries one to one relation to join all the tables


Solution

  • When you are creating the Clinic instance, you need to pass register_user permeameter with Registered_user object like this:

           clinic_user_instances = Registered_user.objects.create(
                username = clinic_user_name,
                email = clinic_email,
                token = token,
                is_clinic=True
            )
            
            # No need to call additional save() method
            clinic_instances = Clinic.objects.create(
                clnc_name = clinic_name,
                clnc_phone = clinic_phone,
                clnc_contact_name = contact_name,
                clnc_Job_Title = Job_Title,
                clnc_address_line1 = address_line1,
                clnc_address_line2 = address_line2,
                clnc_county = country,
                clnc_postcode = postcode,
                register_user = clinic_user_instances 
            )