如何通过UserChangeForm保存条目?

时间:2019-04-03 21:33:03

标签: django

我创建了一个UserChangeForm来编辑教师信息。当我提交表单时,它没有将条目保存到数据库中。

我需要两个用户来使用两个自定义视图,但是userchangeform不会将主题保存到教师的表中。同时,用户创建表单完全没有问题。 models.py


class User(AbstractUser):
    users = (
        ('student', 'Student'),
        ('teacher', 'Teacher'),
)
class Teacher(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    user.user_type = "teacher"
    id = models.AutoField(unique=True, primary_key=True)
    subject = models.CharField(max_length=20)

    #return the doctors' name
    def __str__(self):
        return str(self.user)

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        if instance.user_type == "student":
            Student.objects.create(user=instance)
        elif instance.user_type == "teacher":
            Teacher.objects.create(user=instance)

post_save.connect(create_user_profile, sender=User)

forms.py

class TeacherForm(UserChangeForm):
    class Meta:
        model = Teacher
        fields = ('subject',)

views.py

def Edit_Teacher(request):
    if request.method == 'POST':
        form = TeacherForm(request.POST, instance=request.user)

        if form.is_valid():
            form.save()
            return redirect('index')
    else:   
        form = TeacherForm(request.POST, instance=request.user)
        args = {'form':form}
        return render(request, 'registration/edit_teacher.html', args)

1 个答案:

答案 0 :(得分:0)

如果您使用的是ModelForm,则需要传递该模型的实例以更新对象。因此,您需要根据提供的代码,传递与登录用户有关的Teacher实例。

views.py

def edit_teacher(request):
    try:
        teacher = request.user.teacher
    except AttributeError:
        raise  # Deal with error here

    if request.method == 'POST':
        form = TeacherForm(request.POST, instance=teacher)

        if form.is_valid():
            form.save()
            return redirect('index')

    form = TeacherForm(instance=teacher)
    cxt = {'form':form}
    return render(request, 'registration/edit_teacher.html', cxt)