Home > Software design >  django assign User to a model
django assign User to a model

Time:09-04

I want to assign a User to a Model in django, I created a custom User model and sign-up/sign-in Forms but now I want to Assign a User model to another model named Customer whenever a new user is Created Here he the Customer model

class Customer(models.Model):
id = models.AutoField(primary_key=True)
User = models.OneToOneField(
    Account, on_delete=models.CASCADE, null=True, blank=True)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, default='0', null=True, blank=True)
address = models.CharField(
    max_length=200, default=' ', null=True, blank=True)
city = models.CharField(max_length=200, default=' ', null=True, blank=True)

def __str__(self):
    if self.name == None:
        return "ERROR-CUSTOMER NAME IS NULL"
    return self.name

Note: I can assign the User manually in the Database and It lists All the Users but I want it to do it itself when a new user is created

CodePudding user response:

I think it would be better to extend the User model, and add more fields rather than creating a new model (which has a User onetoonefiled in it). Something like this:

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

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True)
    location = models.CharField(max_length=30, blank=True)
    birth_date = models.DateField(null=True, blank=True)

This is the kind of approach I use in my projects.
Here you have the default User model fields:
User model default fields You don't need to add these in your Profile class.

I based this on this article: How to extend User Django Model

don't forget to add to the admin.py:

from django.contrib import admin
from .models import Profile

# Register your models here.

admin.site.register(Profile)

to see the Profiles in the admin page

CodePudding user response:

Got it fixed by setting the user in the Customer model when a user is created

Customer.objects.create(user=request.user, name=username, email=email, phone=phone)
  • Related