0

Within my application i would like "parent users" to add other users. It should add them as a user to the custom user model but it should not provide an option to set a password, instead set a random password. Currently I cannot seem to hide the password on the form. So this is step one the user that is adding should not have see the password fields, then after adding the user it should set random passwords and e-mail them the password.

If this is the wrong direction, what is the other options. Form

class AddStaffMember(UserCreationForm):
    usrtype = forms.ChoiceField(choices=[('Admin','Admin'),('Manager','Manager'),('Employee','Employee')],label="User Type: See below for descriptions" )
    password1 = forms.HiddenInput()
    password2 = forms.HiddenInput()
    class Meta:
        model = get_user_model()
        fields = ("firstname","lastname","email","usrtype","password1","password2")
        labels = {
            "firstname": _("First Name"),
            "lastname": _("Last Name"),
            "email": _("E-mail"),
        }
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

Model

class AddStaffView(CreateView):
    form_class = forms.AddStaffMember
    success_url = reverse_lazy('nodisoapp:home')
    template_name = "scrty/addstaff.html"
    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.password1 = get_random_string(length=8)
        self.object.password2 = self.object.password1
        self.object.save()
        message = render_to_string('scrty/invite_email.html',{
        'user':self.object.firstname,
        'username':self.object.email,
        'sender':self.request.user.firstname,
        'domain':'127.0.0.1:8000/nodiso',
        'password':self.object.password,
        })
        mail_subject = 'You have been invited to join Nodiso'
        email = EmailMessage(mail_subject, message, to=[self.object.email])
        email.send()
        return super(AddStaffView, self).form_valid(form)
Hennie
  • 65
  • 8
  • Did you try removing the `password` fields from your form? Also, instead of setting a random password yourself, use [`user.set_unusable_password()`](https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User.set_unusable_password). – xyres Nov 21 '17 at 16:22
  • yes i did it it does not remove them. – Hennie Nov 22 '17 at 06:12
  • Oh, right. That's happening because you've inherited the `AddStaffMember` form from `UserCreationForm`. This question might help: https://stackoverflow.com/questions/15557257/django-remove-a-field-from-a-form-subclass – xyres Nov 22 '17 at 08:46

0 Answers0