0

I'm developing web app in only admin can create new user. In my app there are two models one is for creating user and another is for creating user profile as below.

class User(AbstractBaseUser):
    User_Type = [
        ('admin', 'Admin'),
        ..............
    ]
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    email = models.EmailField(_('email address'), unique=True)
    username = models.CharField(_("Username"), max_length=50, unique=True)
    user_type = models.CharField(_("User Type"), choices=User_Type, default='none',)
    ..............

and another model is for storing user information.

class UserProfile(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.OneToOneField(User, verbose_name=_("User"), on_delete=models.CASCADE)
    first_name = models.CharField(_("First name"), max_length=50)
    last_name = models.CharField(_("Last name"), max_length=50)
    dob = models.DateField(_("D.O.B"), auto_now=False, auto_now_add=False, blank=False, null=False)
    profile_image = models.ImageField(_("Profile picture"), upload_to='user/profile/', blank=True)
   ............

what i want here is if any use is created by admin it automatically redirect to the profile page to add profile also.

forms.py code is here.

class CustomUserCreationForm(UserCreationForm):

    class Meta(UserCreationForm):
        model = User
        fields = ('email', 'username', 'user_type')

and

class UserProfileForm(forms.ModelForm):

    class Meta:
        model = UserProfile
        fields = '__all__'

and views.py is here

class AddUserView(CreateView):
    model = User
    form_class = CustomUserCreationForm
    template_name = "users/add-user.html"

    def form_valid(self, form):
        form.save()
        return redirect('users:profile-add')

I tried some posted solution on stackoverflow but none is working. Creating user profile pages in Django Creating a extended user profile I didn't know what I'm doing wrong.

1 Answers1

1

You can use post signal for configuring your profile after your user is created.

Please check below code.

In models.py

def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(username=instance)


post_save.connect(create_user_profile, sender=User)
Joker09
  • 93
  • 7
  • 1
    It is a function, you have to define it after UserProfile. Please find the below link for your reference https://stackoverflow.com/questions/12567995/django-how-to-create-extra-objects-while-a-user-creating – Joker09 Dec 10 '19 at 04:46