-1

I have two classes Customer and Restaurant that have OneToOneField with the django built in User. When I go to a page I am trying to determine which User it is. What I am doing doesnt work because the User model will always return True for having a restaurant attribute, so it never makes it past the first if statement...

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 dashboard(request):
    if User.restaurant:
        return render(request,'usermanage/dashboard_restaurant.html')
    elif User.customer is not None:
        return redirect(request, 'usermanage/dashboard.html')
    else:
        return render(request, 'usermanage/dashboard.html')
ratrace123
  • 976
  • 4
  • 12
  • 24
  • You should set a flag or status field or role field which describes which type of user, in your `CustomUser` model. Then, you can differentiate between the two without any complications. Without that, Django has no way distinguishing between a Restaurant user and a Customer user. – zaidfazil Jul 28 '17 at 06:34

1 Answers1

0

Your view file is checking the restaurant attribute on the User model and not the instance, this is not how you use Models in Django, please read the documentation on Django's ORM for the correct usage. You can access the authenticated user from the request with request.user. You should do something like:

def dashboard(request):
    user = request.user
    if user and hasattr(user, 'restaurant'):
        return render(request,'usermanage/dashboard_restaurant.html')
    elif user and hasattr(user, 'customer') is not None:
        return redirect(request, 'usermanage/dashboard.html')
    else:
        return render(request, 'usermanage/dashboard.html')

Make sure you read the documentation on Django's OneToOneField and ORM. If you refer to the One-to-one relationship documentation you would read:

from django.core.exceptions import ObjectDoesNotExist  
try:  
    p2.restaurant  
except ObjectDoesNotExist:  
    print("There is no restaurant here.")  

There is no restaurant here.

You can also use hasattr to avoid the need for exception catching:

hasattr(p2, 'restaurant')  

False

One of these two example should be how you check for the missing restaurant on your user.

A. J. Parr
  • 7,731
  • 2
  • 31
  • 46
  • i was trying request.user for a while with no luck. I am still getting an error with this method: `Exception Value: User has no restaurant.` – ratrace123 Jul 28 '17 at 05:40