Issue
i have two forms (OwnerCreateForm, EmployeesCreateForm) and 3 models (Profile, Company). when owner signup he creates the company and his own User object. after the owner login, he can created Employees. i need to associate the owners company to the employees. here is the models i'm using:
class Company(models.Model):
company_name = models.CharField(max_length=100, unique=True)
address = models.CharField(max_length=100)
def __str__(self):
return self.company_name
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
company = models.ForeignKey(Company, on_delete=models.CASCADE)
is_owner = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
is_manager = models.BooleanField(default=False)
is_systemAdmin = models.BooleanField(default=False)
def __str__(self):
return '{} Profile'.format(self.user.username)
and here the forms:
from django.contrib.auth.forms import UserCreationForm
from .models import Company
from django import forms
class CompanyForm(forms.ModelForm):
class Meta:
model = Company
fields = ('company_name', 'address')
class OwnerCreateForm(UserCreationForm):
class Meta:
fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2')
model = get_user_model()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['username'].label = 'Display Name'
self.fields['email'].label = "Email Address"
class EmployeesCreateForm(UserCreationForm):
is_admin = forms.BooleanField(required=False)
is_manager = forms.BooleanField(required=False)
is_systemAdmin = forms.BooleanField(required=False)
class Meta:
fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2')
model = get_user_model()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['username'].label = 'Display Name'
self.fields['email'].label = "Email Address"
and here is my views:
from django.shortcuts import render, redirect
from .forms import OwnerCreateForm, EmployeesCreateForm, CompanyForm
from .models import Profile
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .models import Profile,User
def create_profile_for_employee(form, company=None, is_owner = False):
profile = Profile()
username_employee = User(username=form.cleaned_data.get('username'))
profile.company = username_employee.profile.company.pk
profile.is_owner = form.cleaned_data.get('is_owner', False)
profile.is_admin = form.cleaned_data.get('is_admin', False)
profile.is_manager = form.cleaned_data.get('is_manager', False)
profile.is_systemAdmin = form.cleaned_data.get('is_systemAdmin', False)
def registration_owner(request):
if request.method == "POST":
form = OwnerCreateForm(request.POST)
company = CompanyForm(request.POST)
if form.is_valid() and company.is_valid():
company.save()
form.save()
messages.success(request, f'Your Account has been Created! You are now able to log in')
return redirect("accounts:login")
else:
form = OwnerCreateForm()
company = CompanyForm()
context = {
'title': 'Sign up Owner',
'form': form,
'company': company
}
return render(request, "accounts/signup.html", context)
@login_required()
def registration_employees(request):
if request.method == "POST":
form = EmployeesCreateForm(request.POST)
if form.is_valid():
form.save()
create_profile_for_employee(form)
messages.success(request, f'Your Account has been Created! You are now able to log in')
return redirect("accounts:login")
else:
form = EmployeesCreateForm()
context = {
'title': 'Sign up Employees',
'form': form,
}
return render(request, "accounts/signup.html", context)
@login_required()
def profile_view(request):
return render(request, "accounts/profile.html")
as you can see in create_profile_for_employee(), I am trying to create the profile of the employees manually, the i cannot access the owners company. any help will be highly appreciated thank you, best
please note that at the moment i am login as the owner. because only the owner can create employees users.
Solution
Please alternate your models logic. I have simplified it for you. Your views will work more flexible this way. While Signing Up, First a user object is created then passed to the company object as FK. Now when you would add employee, it would be easy assigning role and the company to the employees. Further you can play with modelling logic according to your exact need by doing minor changes. Best of luck :)
class Company(models.Model):
owner = models.ForeignKey(Owner, on_delete=models.CASCADE)
company_name = models.CharField(max_length=100, unique=True)
address = models.CharField(max_length=100)
def __str__(self):
return self.company_name
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
class Owner(models.Model):
profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
class Employee(models.Model):
profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
role = models.ChoiceField(choices=STATUS_CHOICES)
company=ForeginKey(Company,on_delete=models.CASCADE)
STATUS_CHOICES = (
(1, _("Admin")),
(2, _("Manager")),
(3, _("System Admin"))
)
Answered By - Zulqarnain Naveed
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.