基本上,我试图通过使用 OneToOne 模型来获取当前用户类型,您可以在下面看到并显示每个模型特定的不同模板“部分”。我研究了一下,发现了 type() 和 hasattr()。我想知道是否有任何方法可以在模板中使用它们,或者您有更好的建议吗?谢谢!
模型.py
class Type1(models.Model):
user = models.OneToOneField(User)
company_name = models.CharField(max_length=100)
def __unicode__(self):
return self.company_name
class Type2(models.Model):
user = models.OneToOneField(User)
first_name = models.CharField(max_length=30)
second_name = models.CharField(max_length=30)
def __unicode__(self):
return self.first_name
视图.py
def Type1Registration(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/')
if request.method == 'POST':
form = Type1Form(request.POST)
if form.is_valid():
user = User.objects.create_user(username=form.cleaned_data['username'],
email=form.cleaned_data['email'], password=form.cleaned_data['password'])
user.save()
type1 = Type1(user=user, company_name=form.cleaned_data['company_name'])
type1.save()
return HttpResponseRedirect('/')
else:
return render(request, 'type1_register.html', {'form': form})
else:
form = Type1Form()
context = {'form': form}
return render(request, 'type1_register.html', context)
def Type2Registration(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/')
if request.method == 'POST':
form = Type2Form(request.POST)
if form.is_valid():
user = User.objects.create_user(username=form.cleaned_data['username'],
email=form.cleaned_data['email'], password=form.cleaned_data['password'])
user.save()
type2 = Type2(user=user, first_name=form.cleaned_data['first_name'],
second_name=form.cleaned_data['second_name'])
type2.save()
return HttpResponseRedirect('/')
else:
return render(request, 'type2_register.html', {'form': form})
else:
form = Type2Form()
context = {'form': form}
return render(request, 'type2_register.html', context)