我无法更新表单集

时间:2019-08-27 16:10:49

标签: django django-forms

我无法使用嵌入式表单进行更新。 我以为以前有可能,但是没有。 我正在尝试解决它,但是没有用。 我加了 我将张贴任何其他必要的物品。 “ ID 这是必填栏。 用户 具有该用户的配置文件已存在。 “ 我有一个错误。

#view

class UserEdit(generic.UpdateView):
    model = User
    form_class = forms.UserUpdateForm
    template_name = 'accounts/accounts_edit.html'
    success_url = reverse_lazy('person:myaccount')

    def get_object(self):
        return get_object_or_404(User, pk=self.request.user.user_id)
#model
class User(AbstractBaseUser, PermissionsMixin):
      username_validator = UnicodeUsernameValidator()

      user_id = models.UUIDField(default=uuid_lib.uuid4,
                              primary_key=True, editable=False)
      username = models.CharField(_('username'), unique=True, max_length=50,validators=[username_validator],error_messages={
              'unique': _("A user with that username already exists."),
          },)

class profile(models.Model):
      image = models.ImageField(upload_to='profile/',default='profile/default.jpg')
      first_name = models.CharField(_('first name'), max_length=30, blank=True,null=True)
      last_name = models.CharField(_('last name'), max_length=150, blank=True,null=True)
      birthday = models.DateField(_('birthday',),null=True)
      user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,)


#form
class ProfileUpdateForm(BaseModelForm):

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

ProfileFormSet = inlineformset_factory(User,profile,form=ProfileUpdateForm,extra=0)


class UserUpdateForm(mixins.ModelFormWithFormSetMixin,BaseModelForm):

    formset_class = ProfileFormSet
    class Meta:
        model = User
        fields = ('username','email',)
#mixin
class ModelFormWithFormSetMixin:

    def __init__(self, *args, **kwargs):
        super(ModelFormWithFormSetMixin, self).__init__(*args, **kwargs)
        self.formset = self.formset_class(

            instance=self.instance,

            data=self.data if self.is_bound else None,
        )

    def is_valid(self):
        return super(ModelFormWithFormSetMixin, self).is_valid() and self.formset.is_valid()

    def save(self, commit=True):
        saved_instance = super(ModelFormWithFormSetMixin, self).save(commit)
        self.formset.save(commit)
        return saved_instance

0 个答案:

没有答案