Issue
When registering, I’d like a moderator to manually set users as active instead of allowing them to be automatically set as active. Here’s what I’m using in my users/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')
password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=password)
# login(request, user)
# messages.success(request, f'Your account has been created! You are now able to log in!')
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=get_upload_path)
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)
Edit:
So, for other’s reading this, this is what worked for me: In signals.py, I placed:
from django.dispatch import receiver
from django.db.models.signals import pre_save
from django.contrib.auth.models import User
@receiver(pre_save, sender=User)
def set_new_user_inactive(sender, instance, **kwargs):
if instance._state.adding is True:
print("Creating Inactive User")
instance.is_active = False
else:
print("Updating User Record")
Solution
There are many ways to do what you want. But, I would recomment you to signals to acheive the goal. Also, signals are pretty important as you go far so better use that from now. Add this signals to models.py
.
from django.dispatch import receiver
from django.db.models.signals import post_save
from django.contrib.auth.models import User
@receiver(post_save, sender=User)
def user_to_inactive(sender, instance, created, update_fields, **kwargs):
if created:
instance.is_active = False
Now, lets talk little bit about
Django_signals. They are like callback, after you do something, it will call the connected function. reciever
decorator is to connect the signal and there is pre_save
argument which specifies that call user_to_inactive
fuction before the save method of user is called, sender
is the model which is going to send the signals to the function. So, when instance is created, we will make user instance
‘s is_active
to false.
Answered By – Biplove Lamichhane
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0