TypeError: __init __ () получил неожиданный аргумент ключевого слова 'instance' для настраиваемого пользователя в Django - PullRequest
1 голос
/ 19 июня 2020

Когда я пытаюсь зарегистрировать специального пользователя или когда я пытаюсь просмотреть профиль пользователя, вошедшего в систему, я получаю эту ошибку. Я не уверен, почему я получаю эту ошибку. Вот мой код, пожалуйста, подскажите, где я делаю не так. Заранее благодарю

urls.py

# urls.py
path('register/', RegisterView.as_view(template_name='users/register.html'), name='register'),
path('profile/', user_views.profile, name='profile'), 

models.py

# models.py
class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')

    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

        img = Image.open(self.image.path)
        if img.height > 300 or img.width > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            img.save(self.image.path)

class User(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    username = models.CharField(max_length=254, unique=True)
    active = models.BooleanField(default=True)
    staff = models.BooleanField(default=False)  # a admin user; non super-user
    admin = models.BooleanField(default=False)  # a superuser
    # notice the absence of a "Password field", that is built in.
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []  # Email & Password are required by default.

    objects = UserManager() ```

forms.py

# forms.py
class RegisterForm(forms.Form):
    password = forms.CharField(widget=forms.PasswordInput)
    password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput)

    class Meta:
        Model = User
        fields = ('email',)

    def clean_email(self):
        email = self.cleaned_data.get('email')
        qs = User.objects.filter(email=email)
        if qs.exists():
            raise forms.ValidationError("email is taken")
        return email

    def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super(UserAdminCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        # user.active = False
        if commit:
            user.save()
        return user

class UserUpdateForm(forms.Form):
    email = forms.EmailField()

    class Meta:
        Model = User
        fields = ['username', 'email']


class ProfileUpdateForm(forms.Form):
    class Meta:
        Model = Profile
        fields = ['image'] ```

views.py

# views.py
@login_required
def profile(request):
    if request.method == 'POST':
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
        if u_form.is_valid() and p_form.is_valid():
            u_form.save()
            p_form.save()
            messages.success(request, f'Your account has been updated!!')
            return redirect('profile')
    else:
        u_form = UserUpdateForm(instance=request.user)
        p_form = ProfileUpdateForm(instance=request.user.profile)

    context = {
        'u_form': u_form,
        'p_form': p_form
    }

    return render(request, 'users/profile.html', context)

class RegisterView(CreateView):
    form_class = RegisterForm
    template_name = 'users/register.html'
    success_url = 'users/login.html', 

1 Ответ

0 голосов
/ 19 июня 2020

Определите, какая функция вызывает эту ошибку, и попробуйте добавить метод __init__, который получает ваши аргументы.

def __init__(self, *args, **kwargs):
...