If somebody has this kind of issue, answer is below, did it :)
I have two apps (accounts and company).
accounts/models.py
class Organization(models.Model):
organization_name = models.CharField(max_length=20)
#custom user model
class NewUser(AbstractBaseUser):
which_organization = models.ForeignKey(Organization, on_delete = models.CASCADE, null=True, blank=True)
#other fields
company/models.py
from accounts import models as accounts_model
class Branch(models.Model):
branch_name = models.ForeignKey(
accounts_model.Organization, on_delete = models.CASCADE, null=True, blank=True)
#other fields
company/forms.py
from .models import Branch
class BranchForm(forms.ModelForm):
class Meta:
model = Branch
fields = '__all__'
company/views.py
from .forms import BranchForm
def some_function(request):
form = BranchForm()
if request.method == 'POST':
form = BranchForm(request.POST, request.FILES)
if form.is_valid():
form.save(commit=False)
form.branch_name = request.user.which_organization
print("User organization: ", request.user.which_organization)
form.save()
return render(request, 'company/index.html', {'form': form})
P.s. Everything works well. I am able to print the user's organization with
print("User organization : ", request.user.which_organization)
But cannot save it with
form.branch_name = request.user.which_organization
in views.py. Instead of getting exact organization name of the user, created object lists all organization names...
How to achieve it?)
Did it :D
def some_function(request):
form = BranchForm()
if request.method == 'POST':
form = BranchForm(request.POST, request.FILES)
if form.is_valid():
another_form = form.save(commit=False)
another_form.branch_name = Organisation.objects.get(id= request.user.which_organization.id )
new_form.save()
return render(request, 'company/index.html', {'form': form})
Try passing an instance of the Organisation model,
def some_function(request):
form = BranchForm()
if request.method == 'POST':
form = BranchForm(request.POST, request.FILES)
if form.is_valid():
form.save(commit=False)
organisation_instance = Organisation.objects.get(id = request.user.which_organization.id )
form.branch_name = organisation_instance
print("User organization: ", request.user.which_organization)
form.save()
return render(request, 'company/index.html', {'form': form})