Issue
I'm working on a project that should handle two types of users. normal users and teachers.
I created one major model. actually I extended AbstractUser built-in django model and added some other fields to it. one of extra fields is is_teacher that is BooleanField and default is False. for users registration I created ModelForm from model User that I extended before. and while registration I set default value for is_teacher = False to specify that this user is normal user. and for teachers registration is_teacher = True. This is ok for both users and teachers login and redirecting them to their panel. but issue is coming after that. I need third model for something else. I need to have ManyToMany field in third model with NORMAL users and TEACHERS; both of them but I have only one model. actually I didn't separate users and teachers models from each other. because of that I don't know how to specify ManyToMany relation with users model and ManyToMany relation with teachers. There is something that I can do (maybe) is creating two types of models one for users and one for teachers and in respect of those two models I have to create two login page and two profile and two registration and then maybe I can create third model as I told you. The question is: Is that true to have two model one for users and one for teachers... ? Is there any solution except of this. Im new to django explain it clearly, please.
Model Form for third_model:
class RequestForm(forms.ModelForm):
class Meta:
model = ThirdModel
fields = ("height", "age", "address")
widgets = {
"user": "hidden"
}
View for saving data in ThirdModel:
@login_required
def request_plan(request):
form = RequestForm(request.POST or None)
if form.is_valid():
user = request.POST.get('username')
form.save(commit=False)
form.save()
context = {
"request_form": form
}
return render(request, "plan/request.html", context)
class User(AbstractUser):
SEX_CHOICES = (
("male", "Male"),
("female", "Female")
)
sex = models.CharField(max_length=6, choices=SEX_CHOICES)
bio = models.CharField(max_length=100)
is_coach = models.BooleanField(max_length=100, default=False)
Solution
Why not to do as following:
class ThirdModel(models.Model):
teachers = models.ManyToManyField(User, related_name='third_model_teachers')
normal_users = models.ManyToManyField(User, related_name='third_model_normals')
You have 2 users user1
and user2
You can add first as teacher:
third_model.teachers.add(user1)
third_model.normal_users.add(user2)
To get all third_model where user a teacher.
user1.third_model_teachers.all()
To get all third_models where user a normal users
user2.third_model_normals.all()
If you have any questions please comment.
Answered By - Sergey Pugach
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.