ratrace123 ratrace123 - 1 year ago 63
Python Question

How to create/signup different User types

I am trying to create two Users; Customers and Restaurants. I used the OneToOneField to relate these to the Django User model. I am confused on how I should go about creating the specific type of user. When I create the user how do I differentiate between which is a Customer and which is a Restaurant? This is what I have thus far, it seems to work but dont feel it is very elegant..

models.py

class Restaurant(models.Model):
restaurant_user = models.OneToOneField(User, on_delete=models.CASCADE)
restaurant_name = models.TextField(max_length=50)
about = models.CharField(max_length=500)


class Customer(models.Model):
customer_user = models.OneToOneField(User, on_delete=models.CASCADE)
about = models.CharField(max_length=500)


views.py

def signup_customer(request):
if request.method == 'POST':
form = SignupForm(request.POST)
if form.is_valid():
first_name = request.POST['first_name']
last_name = request.POST['last_name']
username = request.POST['username']
password = request.POST['password']
email = request.POST['email']

#TO DO CHECK IF IT ALREADY EXISTS

user1 = User.objects.create_user(username=username, password=password,
email=email)
user1.save()
user = Customer(customer_user=user1)

login(request, user1)
return redirect('dashboard')

Answer Source

You will be able to access the different relations from the User object by going:

user = User.objects.first()
user.restaurant
user.customer

So, to do what it sounds like you want to do(assign specific types to each User account), you'll have to check if they have a restaurant or customer related to their account.

What I would recommend doing is create a separate user profile table that stores additional information specific to the user that is similar between Customer and Restaurants and have a flag that you can check on there.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download