UNIQUE约束失败:更新用户信息时,auth_user.username

时间:2019-04-28 17:28:52

标签: django django-users

我正在尝试为用户提供通过ModelForm更改其名字/姓氏的选项。当我按Submit时,我遇到 UNIQUE约束失败:auth_user.username 错误。这是我的代码:

students / forms.py:

class EditProfileForm(UserChangeForm):
    def clean_password(self):
        # Overriding the default method because I dont want user to change 
        # password
        pass

     class Meta:
        model = User
        fields = (
            'first_name',
            'last_name',
        )

students / views.py:

User = get_user_model()

def student_profile_view(request, slug):
    if request.method == 'GET':

        # forms
        edit_name_form = EditProfileForm(instance=request.user)

        context = {
            'edit_name_form': edit_name_form,
        }
        return render(request, "students/profile.html", context)

class ChangeNameView(SuccessMessageMixin, UpdateView):
        template_name = 'students/edit_profile.html'
        model = User
        form_class = EditProfileForm
        success_message = "Your name has been updated"

        def post(self, request, *args, **kwargs):
            form = self.get_form()
            if form.is_valid():
            form.instance.student_profile = StudentProfile.objects.get(slug=request.user.student_profile.slug)
                return self.form_valid(form)
            else:
                return self.form_invalid(form)

        def form_valid(self, form):
            """If the form is valid, save the associated model."""
            form.instance.username = self.request.user
            self.object = form.save(commit=False)
            return super().form_valid(form)

        def get_success_url(self):
            return reverse('students:student_profile_view', kwargs={'slug': self.object.student_profile.slug})

也可以,用户模型是带有StudentProfile的外键。

students / models.py:

class StudentProfile(models.Model):
    user = models.OneToOneField(User, related_name='student_profile', on_delete=models.CASCADE)
    slug = models.SlugField(blank=True, unique=True)
    avatar = models.ImageField(upload_to='student_profile/', null=True, blank=True)
    description = models.CharField(max_length=120, null=True, blank=True)

    objects = models.Manager()

    def __str__(self):
        return self.user.username

    def get_absolute_url(self):
        return reverse("students:student_profile_view", kwargs={"slug": self.slug})

我对基于类的视图还很陌生,所以也许我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

我假设您在表单内没有用户,因此您需要表单

def get_context_data (self, *args, **kwargs)
    ctx = super().get_context_data(*args, **kwargs)
    if self.request.method == 'POST':
        ctx['form'] = EditProfileForm(instance=self.request.user)

并删除def form_valid()