我有2种用户类型,老师和学生。我构建了视图以便能够编辑学生档案。但我也需要一个不同的老师。我不想要2个观点,因为那是毫无意义的。现在,对于老师来说,它按预期工作,但出于某种原因,学生会显示与教师相同的形式......学生具有不同的属性,因此我需要展示不同的形式。
@login_required
def profile_edit(request):
user = request.user
student = request.user.student
teacher = request.user.teacher
if user == teacher.user:
if request.method != 'POST':
form = TeacherEditForm(instance=teacher)
else:
form = TeacherEditForm(request.POST, instance=teacher)
if form.is_valid():
user.email = form.cleaned_data['email']
user.save()
form.save()
return redirect('index')
elif user == student.user:
if request.method != 'POST':
form = StudentEditForm(instance=student)
else:
form = StudentEditForm(request.POST, instance=student)
if form.is_valid():
user.email = form.cleaned_data['email']
user.save()
form.save()
return redirect('index')
context = {
"form": form,
}
return render(request, "registration/profile_edit.html", context)

我认为将数据传递给学生和教师的方式有问题,而且视图可以区分用户类型。
答案 0 :(得分:1)
像这样但删除
User.student = property(lambda p: Student.objects.get_or_create(user=p)[0])
User.teacher = property(lambda p: Teacher.objects.get_or_create(user=p)[0])
@login_required
def profile_edit(request):
user = request.user
try:
student = Student.objects.get(user=user)
s=True
except: teacher = Teacher.objects.get(user=user)
if not s:
if request.method != 'POST':
form = TeacherEditForm(instance=teacher)
else:
form = TeacherEditForm(request.POST, instance=teacher)
if form.is_valid():
user.email = form.cleaned_data['email']
user.save()
form.save()
return redirect('index')
elif s:
if request.method != 'POST':
form = StudentEditForm(instance=student)
else:
form = StudentEditForm(request.POST, instance=student)
if form.is_valid():
user.email = form.cleaned_data['email']
user.save()
form.save()
return redirect('index')
context = {
"form": form,
}
return render(request, "registration/profile_edit.html", context)