extending the user model to create a user2 model - python

I have a requirement of two types of login in my django project where one login is for students and one login is for teachers.
I have gone through the Django documentation and other internet resources, and I have come up with a simple design solution but I am not sure about the pros and cons as I am still quiet new to Django.
Solution I thought to solve this Problem:
1) For student login, I have succesfully integrated django-allauth and it is working fine.
2) Now for the teacher login, I am thinking to build a model as follows:
class Teacher(models.Model):
teacher = models.OneToOneField(User,unique=True)
identifier = models.CharField(max_length=128)
#other fields
3) Then two forms over this model - Signup and Login for teachers and email verification form: Here I thought that I will create teacher object and student object on successful signup but I will set is_active=False and ask for email verification.On successful verification, I will set is_active=True so that a teacher can successfully login.
4) Avoid students from logging in the teachers section and teachers can login in the students section: Here I though of an identifier field to avoid authenticated students to login in the teachers section.
Please can anyone help me by providing your opinion on this solution or by suggesting some better alternative as I am still reading up more and more Django Documentation on this.
Thanks in Advance!

You could create a single model 'user' and define there permissions by adding them to a group.
And have your Django application for teachers check if there in the group teacher.
You could create separate forms or check based on email (name.student# or name# ) and
before saving the model adding the group.
Keeping is_active on False is alway a good idea if you want to verify that a 'user' has given a correct email.

I did an application which needed different permissions levels for Students, Teachers and a few different other User categories. I'm not sure if it's the best way to do it, but I did it by creating one UserProfile, as Eagllus mentioned, which had several categories for what kind of user profile it was. Something like:
PROFILE_CHOICES = (
('TE', 'Teacher'),
('ST', 'Student'),
)
class UserProfile(models.Model):
user = models.ForeignKey(User)
profile_type = models.CharField(max_length=2, choices=PROFILE_CHOICES)
'''other attributes'''
You can then decorate your views so only users of a certain type can access them.
Its not clear to me what you are trying to do in #3. It sounds like you want the user to be added as a teacher and student but only make them active by email verification?
I'm not familiar with django-auth but django-registration provides user registration where user account are activated via email. This may save you a significant amount of work.

Related

What is a good way to store guest user information that may be saved to a permanent user after registration in django?

I have a RESTful django webapp that allows users to take quizzes in a progressive system where the quizzes become increasingly difficult. Their progress is saved when they answer a question. I'm using django-rest-framework.
class User(AbstractUser):
pass
class IntervalsProfile(models.Model):
# Belongs to User model in 1-to-1 relationship
# If User is deleted, then the corresponding IntervalsProfile will be deleted as well
user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile', on_delete=models.CASCADE)
level = models.IntegerField(default=0)
current_level = models.IntegerField(default=0) # Level the user is currently viewing/on
I would like users to be able to play as a guest, and if they so choose, register in order to save their progress. I cannot figure out how to save this guest information or how to save it once they register.
I've searched thoroughly and all the solutions I see are either several years old or seem too cumbersome (such as adding a check for authentication in every view and having 2 cases for each view).
Any advice or guidance would be much appreciated.
if they so choose, register in order to save their progress
Subclass django's User model and add a new field called is_guest = BooleanField. (django has good documentation on how to do this already.)
Ask your users to input just a username when they visit for the first time. (or you can also assign them a random username using something like coolname).
Create a User instance for their chosen username with is_guest=True without any password and now you can save all the game information anyway corresponding to this user.
Tomorrow, when they choose to register, you can simply update the already existing User instance and mark is_guest=False.
EDIT:
If you don't want the added complexity of your own User model, you could also achieve the same without subclassing User model and just adding the is_guest column to the IntervalsProfile model

Django - Team/User relationships

I'm at a loss... I'm just learning Django and I am really rather confused about how to make a field work the way I would like it to.
I understand that Django has a native "Groups" model. However, I am looking to build my own teams model for customization and practice.
Here is my models.py file for my Users app:
from django.db import models
from django.contrib.auth.models import User
class Team(models.Model):
members = models.ManyToManyField(User)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
admin = models.BooleanField("Admin Status")
Here's where I'm confused. I would like to be able to call the team that the user is part of directly from User.Profile. So, I want to add a field to my Profile class that will automatically populate with the team name when a user is added to a team.
A potential problem I can see is that, currently, I can assign a user to multiple teams. This doesn't bother me, perhaps I can have a Profile model field that automatically populates with a list of all the teams that the user is associated with. Regardless, I can't figure out what type of field I would need to use, or how to do this.
Does that make sense?
A potential problem I can see is that, currently, I can assign a user to multiple teams.
Indeed, you can however easily retrieve the Teams the myprofile object is a member of with:
Team.objects.filter(members__profile=myprofile)
You thus can make a property for the Profile model:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
admin = models.BooleanField("Admin Status")
#property
def teams(self):
return Team.objects.filter(
members__profile=self
)
Then you thus access the Teams of a myprofile with myprofile.teams.
So, I want to add a field to my Profile class that will automatically populate with the team name when a user is added to a team.
From my limited knowledge of database, you can add a name field to your Team model.
Keeping in mind your requirement as mentioned in question, i would suggest you to use django reverse relations to get all the teams the profile is associated with
user_teams = User.objects.get(id='user_id').profile_set.all()[0].team_set.all()
to know more about django ORM reverse relation, here is a very short article

Connect logged user with model

I'm working on small project with Django framework. And as I can implement usage of authentication mechanism, that I can find a solution how to use information about logged user with model I define.
In example. I have model that will store information about QSL cards, and I want to have option that depends on which user is logged, his/her QSL cars will be shown from database.
I search here and in docs.djangoproject.com but without success.
Thanks in advance for any tips or links.
If you try,
user = request.user
Variable user will have currently logged in user object. You can use this user to filter some models objects where user is foreign key. For e.g posts = Post.objects.filter(user=request.user). If you want to get any specific user information, for e.g username. You can try username = request.user.username

Trouble understaing User Object in Django

I'm learning django and creating a web app where a clients signs up to make a purchase and also a vendor can add his/her product for sale. After reading the documentation on django, I'm still not clear on the User in built Object provided by django. My question is:
Should i use the User in built object to satisfy my requirements. But after reading the documentation it seems the User object is mostly suited for admin privileges/superuser or am i wrong.
Since i will be having 2 Users, meaning having 2 different models in database. There will be 2 different views. The client or users only sees products for sale and vendor only sees his dashboard and products he/she wishes to put up for sale.
Coming from a Java perspective i could just create a Client class and a Vendor class but i want to do this in django and it seems from what i have read from the documentation they suggest to use the User object. Please how do i go about this or could someone give an example of how to go about this. Thanks much appreciated..
You are correct, the java perspective is the database perspective, which is true for django as well:
from django.contrib.auth.models import User
class Client(models.Model):
user = models.OneToOneField(User)
# ... more Client fields here
class Vendor(models.Model):
user = models.OneToOneField(User)
# ... more Vendor fields here
Note that these models allow a user to be a client and a vendor - or none at all. If a user can be only be a client or a vendor, or must be one of those classes, you will need additional validation. The User model will be used for the common features to all, such as authentication or other shared features (e.g. using the email to send a notification)

Giving anonymous users the same functionality as registered ones

I'm working on an online store in Django (just a basic shopping cart right now), and I'm planning to add functionality for users to mark items as favorite (just like in stackoverflow). Models for the cart look something like this:
class Cart(models.Model):
user = models.OneToOneField(User)
class CartItem(models.Model):
cart = models.ForeignKey(Cart)
product = models.ForeignKey(Product, verbose_name="produs")
The favorites model would be just a table with two rows: user and product.
The problem is that this would only work for registered users, as I need a user object. How can I also let unregistered users use these features, saving the data in cookies/sessions, and when and if they decides to register, moving the data to their user?
I guess one option would be some kind of generic relations, but I think that's a little to complicated. Maybe having an extra row after user that's a session object (I haven't really used sessions in django until now), and if the User is set to None, use that?
So basically, what I want to ask, is if you've had this problem before, how did you solve it, what would be the best approach?
I haven't done this before but from reading your description I would simply create a user object when someone needs to do something that requires it. You then send the user a cookie which links to this user object, so if someone comes back (without clearing their cookies) they get the same skeleton user object.
This means that you can use your current code with minimal changes and when they want to migrate to a full registered user you can just populate the skeleton user object with their details.
If you wanted to keep your DB tidy-ish you could add a task that deletes all skeleton Users that haven't been used in say the last 30 days.
Seems to me that the easiest way to do this would be to store both the user id or the session id:
class Cart(models.Model):
user = models.ForeignKey(User, null=True)
session = models.CharField(max_length=32, null=True)
Then, when a user registers, you can take their request.session.session_key and update all rows with their new user id.
Better yet, you could define a "UserProxy" model:
class Cart(models.Model):
user = models.ForeignKey(UserProxy)
class UserProxy(models.Model):
user = models.ForeignKey(User, unique=True, null=True)
session = models.CharField(max_length=32, null=True)
So then you just have to update the UserProxy table when they register, and nothing about the cart has to change.
Just save the user data the user table and don't populate then userid/password tables.
if a user registers then you just have to populate those fields.
You will have to have some "cleanup" script run periodically to clear out any users who haven't visited in some arbitrary period. I'd make this cleanup optional. and have a script that can be run serverside (or via a web admin interface) to clear out in case your client wants to do it manually.
remember to deleted all related entries as well as the user entry.
I think you were on the right track thinking about using sessions. I would store a list of Product id's in the users session and then when the user registers, create a cart as you have defined and then add the items. Check out the session docs.
You could allow people that are either not logged in or don't have an account to add items to a 'temp' cart. When the person logs in to either account or creates a new account, add those items to their 'real' cart. Then by just adding a few lines to your 'add item to cart' and login functions, you can use your existing models.

Categories