python - How can I differentiate between users with lookup -
i have 2 classes customer
, restaurant
have onetoonefield
django built in user
. when go page trying determine user
is. doing doesnt work because user
model return true having restaurant
attribute, never makes past 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) = models.charfield(max_length=500) class customer(models.model): customer_user = models.onetoonefield(user, on_delete=models.cascade) = models.charfield(max_length=500)
views.py
def dashboard(request): if user.restaurant: return render(request,'usermanage/dashboard_restaurant.html') elif user.customer not none: return redirect(request, 'usermanage/dashboard.html') else: return render(request, 'usermanage/dashboard.html')
your view file checking restaurant
attribute on user
model , not instance, not how use models in django, please read documentation on django's orm correct usage. can access authenticated user request request.user
. should like:
def dashboard(request): user = request.user if user , hasattr(user, 'restaurant'): return render(request,'usermanage/dashboard_restaurant.html') elif user , hasattr(user, 'customer') not none: return redirect(request, 'usermanage/dashboard.html') else: return render(request, 'usermanage/dashboard.html')
make sure read documentation on django's onetoonefield , orm. if refer one-to-one relationship documentation read:
from django.core.exceptions import objectdoesnotexist try: p2.restaurant except objectdoesnotexist: print("there no restaurant here.")
there no restaurant here.
you can use hasattr avoid need exception catching:
hasattr(p2, 'restaurant')
false
one of these 2 example should how check missing restaurant
on user.
Comments
Post a Comment