Issue
I have a custom user model and a form that allows admins to add users without having to go to the admin section. I want hide the password fields and set the password to a random generated string. Then send an email to the new user with a link to reset their password.
So far I haven't been able to figure out the first part - hiding the password fields.
The form.py:
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser
class AddCompanyEmployeeForm(UserCreationForm):
class Meta:
model = CustomUser
fields = UserCreationForm.Meta.fields + ('email', 'full_name', 'age')
the view:
from django.views.generic import CreateView, ListView
from django.urls.base import reverse
from .forms import CustomUserCreationForm, AddCompanyEmployeeForm
from .models import CustomUser
class SignUpView(CreateView):
form_class = CustomUserCreationForm
success_url = reverse_lazy('login')
template_name = 'registration/signup.html'
class AddCompanyEmployee(CreateView):
model = CustomUser
template_name = 'manage/add_employee.html'
form_class = AddCompanyEmployeeForm
#success_url = reverse_lazy('directory')
def get_success_url(self):
return reverse('userprofile_detail', kwargs={'pk': self.object.userprofile.pk})
The custom user model:
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import Group
from django.contrib import admin
from django.db.models import Count
from django.db.models.signals import post_save
class CustomUser(AbstractUser):
full_name = models.CharField(max_length=250, null=True)
age = models.PositiveIntegerField(null=True, blank=True)
employee_type = models.ForeignKey(Group, null=True, on_delete=models.SET_NULL, default=1)
employee_start_date = models.DateField(null=True, blank=True)
is_active = models.BooleanField(null=False, default=True)
I have tried a number of approaches including changing the form to
class AddCompanyEmployeeForm(UserCreationForm):
class Meta:
model = CustomUser
fields = ('email', 'full_name', 'age')
So far the password fields continue to be visible regardless of what I try. Any suggestions?
Solution
Apparently password1 and password2 fields are defined in form directly when using UserCreationForm, not in the model. So exclude and fields will have no effect on them.
You have to make the form with ModelForm or Form.
Answered By - Finn
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.