Issue
I am making a blog style website, and for the register form, I decided I want to add a checkbox that says 'I'm a staff member' so that if the form is submitted with this box checked said user is registered as a staff member instead of just a normal member. I know this isn't very secure but in my specific case it would work very well.
I know I could do this by creating a different form only for staff members but I really want to do it with the checkbox. So, the checkbox is there, how can I make it check if it's checked or not to make a staff user?
ANY kind of help is greatly appreciated.
Here is my code:
forms.py
class UserRegisterForm(UserCreationForm):
email = forms.EmailField(
label= 'Correo Electrónico',
required=True,
)
username = forms.CharField(max_length=100, required=True, label='Nombre de Usuario')
password1 = forms.CharField(
label = "Contraseña",
required=True
)
password2 = forms.CharField(
label = "Confirmar Contraseña",
required=True
)
is_teacher = forms.BooleanField(
label='Soy profesor/a',
required=True,
)
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2', 'is_teacher']
views.py
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Tu cuenta se ha creado correctamente, ahora puedes iniciar sesión')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
models.py
class Profile(models.Model):
user = models.OneToOneField(User, 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(Profile, self).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)
Solution
I was able to solve my problem.
I fixed it, by adding a couple things to the code:**
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
user = form.save(commit= False)
username = form.cleaned_data.get('username')
is_teacher = form.cleaned_data.get('is_teacher')
if is_teacher == True:
user.is_staff = True
user.save()
else:
user.is_staff = False
user.save()
messages.success(request, f'Tu cuenta se ha creado correctamente, ahora puedes iniciar sesión')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
First I added 'commit = False' to the 'form.save' so that it would save it but it wouldn't send the information to the database right away (and that's what was messing up the entire thing, it would write everything directly into the database and then it wouldn't change it anymore unless I manually did it through admin), so it holds on to it and then as the code says, if 'is_teacher == True' (that's the checkbox) it will register that user as a Staff member and after that it saves the form again this time sending the data to the database, and if it was the other way around and 'is_teacher == False' then it would just do the same but instead of saying 'user.is_staff = True' it'll say it is false.
I hope I was able to explain myself correctly.
Answered By - winston1420
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.