I have a basic question which can be useful for new Django developers.
I created my own UserProfile in Django. This UserProfile has a specific field called 'type'. This field can have two values (until now maybe more in the future) : Male - M / Female - F :
from django.contrib.auth.models import User
GENDER = (
(M, 'Male'),
(F, 'Female'),
)
class UserProfile(models.Model):
user = models.OneToOneField(User)
type = models.CharField( max_length=2,
choices=GENDER,
default='F')
Basically, I wanted to allow access to restrict access or to adapt page content depending on user Type. Until now, I used a really basic and beginner approach which is to test user type in a view and then process the page:
def OnePage(request):
if request.user.type == 'M':
....
else if request.user.type =='F':
....
Then I also need to adapt the template rendered depending on user type: a male user will not have the same profile page that a Female User.
I am sure there are better ways to do this but as a Django beginner I am quite lost with all of Django possibilities. So if you have any best practices to implement this please tell me (obviously I would like a DRY code I could use on every view!)
Thank you for your help.
To add extra data to User see
Storing additional information about users
Then add the profile to your context and you can use {{profile}} variable in your template
One solution could be to change the base template name depending on the user type:
And in your template :
If you need to do this on every view, you could use a middleware to set this value.
To restrict access, use the user passes test decorator:
Depending on what you want to do, if you need to use very different html for different genders, you can try this approach:
So instead of returning Http resonpse in views, you can make them return TemplateResponse objects and use decorators to change templates, add in general context, and them convert them to HttpResponse.
Or something like a permission check: