0

So I have this models, I add to User Model an avatar:

class ProfileImage(models.Model):
    user = models.OneToOneField(
        verbose_name=_('User'),
        to=settings.AUTH_USER_MODEL,
        related_name='profile',
        on_delete=models.CASCADE
    )
    avatar = models.ImageField(upload_to='profile_image')

I also have a forms for the User model:

class UserRegisterForm(forms.ModelForm):
    username = forms.CharField(label='', widget=forms.TextInput(attrs={'placeholder': 'Username'}))
    email = forms.EmailField(label='', widget=forms.TextInput(attrs={'placeholder': 'Email Address'}))
    email2 = forms.EmailField(label='', widget=forms.TextInput(attrs={'placeholder': 'Confirm Email'}))
    password = forms.CharField(label='', widget=forms.PasswordInput(attrs={'placeholder': 'Password'}))

    class Meta:
        model = User 
        fields = [
            'username',
            'email',
            'email2',
            'password'
        ]

    def clean(self, *args, **kwargs):
        email = self.cleaned_data.get('email')
        email2 = self.cleaned_data.get('email2')
        if email != email2:
            raise forms.ValidationError('El email debe coincidir')
        emails_qs = User.objects.filter(email=email)
        if emails_qs.exists():
            raise forms.ValidationError(
                'El email ya esta en uso'
            )
        return super(UserRegisterForm, self).clean(*args, **kwargs)

I think that if I to the fields of my forms I can see it. So How can I add to my fields the avatar?

1 Answers1

0

I think the best way to achieve this is to create a post_save signal to create a ProfileImage instance for the new user.

https://docs.djangoproject.com/en/3.0/ref/signals/

You can than create a new form like: ProfileImageForm to let the user add a profile image in the same way you created the register form.

See this post for a similar approach: Creating a extended user profile

Rick
  • 211
  • 4
  • 11