【发布时间】:2021-12-16 15:05:39
【问题描述】:
如果有人遇到这种问题,答案如下,是吗:)
我有两个应用程序(帐户和公司)。
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})
附:一切正常。我可以打印用户的组织
print("User organization : ", request.user.which_organization)
但不能用
form.branch_name = request.user.which_organization
在views.py中创建的对象不是获取用户的确切组织名称,而是列出所有组织名称...
如何实现?)
【问题讨论】:
标签: python-3.x django django-models django-views foreign-keys