Django Signals not creating profile after user registration - python

I want the profile to be created once the user registration is complete but I am having to create a profile separate for the existing user.
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from main.models import Membership
# Create your models here.
class Profile(models.Model):
membership = models.OneToOneField(
Membership, on_delete=models.CASCADE, related_name="membership", default="null")
user = models.OneToOneField(
User, on_delete=models.CASCADE, related_name="profile")
couple_with = models.OneToOneField(
User, on_delete=models.CASCADE, related_name="couple_with", blank=True, null=True)
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
maiden_name = models.CharField(max_length=2, blank="")
street_address = models.CharField(max_length=50)
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES, default="Select")
date_of_birth = models.DateField( blank=True, null=True)
address2 = models.CharField(max_length=10)
city = models.CharField(max_length=20)
state = models.CharField(max_length=20)
zip = models.CharField(max_length=5)
country_name = models.CharField(max_length=30)
graduate_year = models.CharField(max_length=4)
def __str__(self):
return(self.first_name + " " + self.last_name)
#receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
user = instance
print(user)
if created:
profile = Profile.objects.create(user=user)
profile.save()
This is what my views.py looks like. I don't know where am I slipping. It is able to create the user once registered but the profile is never created and Admin has to create the profile manually.
def register_account(request):
# check if the user is already logged in
if request.user.is_authenticated:
return redirect("main:home")
# if not logged in
else:
if request.method == 'POST':
form = RegistrationForm(request.POST or None)
# check if the form is valid
if form.is_valid():
user = form.save(commit=False)
duplicate = False
nonWarhawks = False
# for u in users:
# if user.email == u.email:
# error_message = "Email Already Exists"
# duplicate = True
# break
if User.objects.filter(email=user.email).exists():
duplicate = True
# duplicate check
if duplicate:
return render(request, 'accounts/register.html', {"error_message": "Email Already Exists", "form": form})
user.is_active = False
user.save()
# create profile
user.refresh_from_db()
user.profile.copule_with = None
user.profile.first_name = request.POST.get("first_name")
user.profile.last_name = request.POST.get("last_name")
user.profile.maiden_name = request.POST.get("maiden_name")
user.profile.street_address = request.POST.get("street_address")
user.profile.city = request.POST.get("city")
user.profile.zip = request.POST.get("zipcode")
user.profile.country_name = request.POST.get("country_name")
user.profile.graduate_year = request.POST.get("graduate_year")
print(user.profile.first_name)
user.profile.save()
current_site = get_current_site(request)
mail_subject = 'Activate your account.'
message = render_to_string('accounts/acc_active_email.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user),
'protocol': 'http'
})
to_email = form.cleaned_data.get('email')
email = EmailMessage(
mail_subject, message, to=[to_email]
)
email.send()
print("Successfully sent email using the sendgrid api")
return HttpResponse('Please confirm your email address to complete the registration')
# return redirect("daily:home")
else:
form = RegistrationForm(request.POST or None)
return render(request, 'accounts/register.html', {'form': form})

Try this outside your Profile class.
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = Profile.objects.create(user=kwargs['instance'])
post_save.connect(create_profile, sender=User)

You have included your #receiver signal inside your profile class. A signal based method isn't actually part of the class it involves. Remove the indentation so it is on the same level as your class Profile declaration

Related

How can I get my custom user model logged in? AuthenticationForm or my own custom login form won't validate

I've created a custom user model, subclassing AbstractUser.
I have a registration view, template, and a CustomUserCreationForm that seems to work fine, and can register users no problem via the front end.
My issue is getting the user logged in. I can't seem to pass the form validation to authenticate them with. I'm always returned with a None user object
With this line for example, I always get None, this failing verification
user = authenticate(request, email=email, password=password)
# user = User.objects.get(email=email, password=hashed_pass)
# Check if authentication successful
if user is not None:
login(request, user)
return HttpResponseRedirect(reverse("clientcare:portal/dashboard"))
else:
return render(request, "clientcare/login.html", {
"message": "Invalid email and/or password.",
'login_form':LoginForm,
})
Forms
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = User
fields = ('email', 'first_name','last_name' ,'city', 'province','age','gender','phone_number','password1', 'password2',)
class LoginForm(forms.Form):
email = forms.EmailField(max_length=100)
password = forms.CharField(widget = forms.PasswordInput())
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = User
fields = ('email', 'first_name','last_name' ,'city', 'province','age','gender','phone_number',)
Models
# Create your models here.
class UserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, email, password, **extra_fields):
if not email:
raise ValueError('Users require an email field')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
extra_fields.setdefault('is_patient', False)
extra_fields.setdefault('is_provider', True)
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(email, password, **extra_fields)
class User(AbstractUser):
username = None
email = models.EmailField(_('email address'), unique=True)
image_height = models.PositiveIntegerField(null=True, blank=True, editable=False, default="200")
image_width = models.PositiveIntegerField(null=True, blank=True, editable=False, default="200")
date_joined = models.DateTimeField(auto_now=True, null=False, blank=False)
city = models.CharField(null=False, blank=False, max_length=20)
province = models.CharField(null=False, blank=False, max_length=20)
profile_image_url = models.ImageField(null=True, blank=True, upload_to='images/', editable=True)
paid = models.BooleanField(default=False)
phone_number = PhoneField(blank=True, null=True, help_text='Contact phone number', E164_only=False)
in_trial = models.BooleanField(default=True)
recently_active = models.BooleanField(default=True)
gender = models.CharField(choices=(("Male", "Male"),("Female", "Female"), ("Other", "Other")), max_length=6, default="Male", null=False, blank=False)
age = models.SmallIntegerField(max_length=3,null=False, blank=False)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name',]
# classify if the user is a provider or a patient
is_patient = models.BooleanField('Patient status',default=False)
is_provider = models.BooleanField('Provider status',default=False)
def __str__(self):
return f"{self.get_full_name()}"
Login View
def login_view(request):
if request.method == "POST":
login_form = LoginForm(data=request.POST)
if login_form.is_valid():
email = login_form.cleaned_data['email']
password = login_form.cleaned_data['password']
# hashed_pass = bcrypt.hashpw(raw_pass, salt)
# if bcrypt.checkpw(raw_pass, hashed_pass):
user = authenticate(request, email=email, password=password)
# user = User.objects.get(email=email, password=hashed_pass)
# Check if authentication successful
if user is not None:
login(request, user)
return HttpResponseRedirect(reverse("clientcare:portal/dashboard"))
else:
return render(request, "clientcare/login.html", {
"message": "Invalid email and/or password.",
'login_form':LoginForm,
})
else:
return render(request, "clientcare/login.html", {
"message": "Invalid login data. Please try again",
'login_form':LoginForm,
})
else:
return render(request, "clientcare/login.html", {
'login_form':LoginForm,
})
Registration view
def register(request):
# Adding the salt to password
if request.method == "POST":
register_form = CustomUserCreationForm(request.POST)
if register_form.is_valid():
email = register_form.cleaned_data['email']
city = register_form.cleaned_data["city"]
province = register_form.cleaned_data["province"]
first_name = register_form.cleaned_data["first_name"]
last_name = register_form.cleaned_data["last_name"]
phone_number = register_form.cleaned_data["phone_number"]
age = register_form.cleaned_data["age"]
gender = register_form.cleaned_data["gender"]
# Ensure password matches confirmation
password = register_form.cleaned_data["password1"]
confirmation = register_form.cleaned_data["password2"]
if password != confirmation:
return render(request, "clientcare/register.html", {
"messsage": "Passwords must match."
})
# Hashing the password
# hashed = bcrypt.hashpw(password, salt)
# password = hashed
# Attempt to create new user
try:
user = User.objects.create(email=email, city=city, province=province, password=password, first_name=first_name, last_name=last_name, phone_number=phone_number, age=age, gender=gender)
user.save()
except IntegrityError:
return render(request, "clientcare/register.html", {
"message": "ERROR. TRY AGAIN",
})
login(request, user)
return HttpResponseRedirect(reverse("clientcare:index"))
else:
return render(request, "clientcare/register.html", {
"message": "ERROR. PLEASE CONFIRM REGISTRATION INFO",
})
else:
return render(request, "clientcare/register.html",{
'registration_form':CustomUserCreationForm
})
I have my user in settings.py as such:
AUTH_USER_MODEL = 'clientcare.User'
I'm well aware I can use AllAuth or other auth libraries. But I'm trying to understand things on a lower level before using such libraries.
Any help would be appreciated.
Nothing I try seems to work in getting my custom user model logged in. Do I need to write a custom backend? AuthenticationForm doesn't seem to work just as my own login form doesn't seem to validate
HOWEVER, if I update a users password via the admin(with superuser), then the user can login no problem with the updated password.. so my CustomUserChangeForm does the job. What am I missing?
I'm putting a model of my old project here as an example. Here I used the user model as it is and added the fields I wanted to add to the new class that user is also a field there. Django's auth module works as is and no additional coding was required.
from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
from backend.custom_fields import AutoOneToOneField
from backend import definitions
from django.urls import reverse
from django.db.models.signals import post_save
from django.dispatch import receiver
from backend.convert import convert_string_to_url_safe
from random import randint
from backend.image_operation import image_resize, image_convert_to_jpg
EMAIL_PRIVACY_CHOICES = (
(0, _('Display your e-mail address.')),
(1, _('Hide your e-mail address but allow form e-mail.')),
(2, _('Hide your e-mail address and disallow form e-mail.')),
)
PHONE_PRIVACY_CHOICES = (
(0, _('Display your phone no.')),
(1, _('Hide your phone no.')),
)
def avatar_upload_file_name_path(instance, filename_ext):
ext = filename_ext.split('.')[-1]
return f'profile_uploads/{convert_string_to_url_safe(instance.get_full_name)}-{randint(1000, 10000)}.{ext}'
def photo_upload_file_name_path(instance, filename_ext):
ext = filename_ext.split('.')[-1]
return f'profile_uploads/{convert_string_to_url_safe(instance.get_full_name)}-{randint(1000, 10000)}.{ext}'
def resized_photo_upload_file_name_path(instance, filename_ext):
ext = filename_ext.split('.')[-1]
return f'profile_uploads/resized-{convert_string_to_url_safe(instance.get_full_name)}-{randint(1000, 10000)}.{ext}'
class PlatformUser(models.Model):
user = AutoOneToOneField(User, on_delete=models.CASCADE)
slug = models.CharField(max_length=100, null=True, blank=True)
title = models.CharField(max_length=60, blank=True, default='')
description = models.TextField(blank=True, default='')
phone = models.CharField(max_length=25, blank=True, default='')
facebook_address = models.URLField(blank=True, default='')
twitter_address = models.URLField(blank=True, default='')
instagram_address = models.URLField(blank=True, default='')
linkedin_address = models.URLField(blank=True, default='')
youtube_address = models.URLField(blank=True, default='')
site = models.URLField(_('Personal Site'), blank=True)
skype_name = models.CharField(_('Skype Name'), max_length=100, blank=True, default='')
birth_date = models.DateTimeField(_('Birth Date'), blank=True, null=True)
location = models.CharField(_('Location'), max_length=30, blank=True)
photo = models.ImageField(upload_to=photo_upload_file_name_path, blank=True, default='')
photo_resized = models.ImageField(upload_to=resized_photo_upload_file_name_path, blank=True, null=True)
show_photo = models.BooleanField(_('Show avatar'), blank=True, default=True)
show_signatures = models.BooleanField(_('Show signatures'), blank=True, default=True)
show_smilies = models.BooleanField(_('Show smilies'), blank=True, default=True)
email_privacy_permission = models.IntegerField(_('Privacy permission'), choices=EMAIL_PRIVACY_CHOICES, default=1)
phone_privacy_permission = models.IntegerField(_('Privacy permission'), choices=PHONE_PRIVACY_CHOICES, default=1)
auto_subscribe = models.BooleanField(_('Auto subscribe'),
help_text=_("Auto subscribe all topics you have created or reply."),
blank=True, default=False)
post_count = models.IntegerField(_('Post count'), blank=True, default=0)
likes_count = models.IntegerField(default=0)
view_count = models.IntegerField(default=0)
signature = models.TextField(_('Sign'), blank=True, default='', max_length=definitions.SIGNATURE_MAX_LENGTH)
signature_html = models.TextField(_('Sign as HTML'), blank=True, default='',
max_length=definitions.SIGNATURE_MAX_LENGTH)
verification_code = models.CharField(_('Verify Code'), blank=True, default='', max_length=40)
created = models.DateTimeField(_('Created'), auto_now_add=True)
updated = models.DateTimeField(_('Updated'), auto_now=True, null=True)
class Meta:
ordering = ['user']
get_latest_by = 'created'
verbose_name = _('Platform Member')
verbose_name_plural = _('Platform Members')
def __init__(self, *args, **kwargs):
super(PlatformUser, self).__init__(*args, **kwargs)
self.__original_image_filename = self.photo.name
#property
def email(self):
return self.user.email
#property
def get_full_name(self):
full_name = str(self.user.first_name.title())
if len(full_name) > 0:
full_name += " "
full_name += str(self.user.last_name.title())
if len(full_name) == 0:
full_name = self.user.username
return full_name
#property
def username(self):
return self.user.username
#property
def first_name(self):
return self.user.first_name
#property
def last_name(self):
return self.user.last_name
def __str__(self):
return f"[{self.user.first_name} {self.user.last_name}] - ({self.user.email})"
def get_absolute_url(self):
return reverse('profile',
args=[str(self.get_slug())])
def get_slug(self):
if not self.slug:
self.slug = self.user.username
return self.slug
def save(self, *args, **kwargs):
if not self.slug:
self.slug = self.get_slug()
if self.photo and (self.photo.name != self.__original_image_filename or not self.photo_resized):
self.photo_resized = image_resize(400, 400, self.photo)
self.photo = image_convert_to_jpg(self.photo)
super(PlatformUser, self).save(*args, **kwargs)
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
PlatformUser.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
platform_users = PlatformUser.objects.filter(user=instance)
if len(platform_users) > 0:
platform_user = platform_users[0]
else:
platform_user = PlatformUser.objects.create(user=instance)
platform_user.save()
as you could see there are receivers for creating my own platform user row on database when user created.
This way is simple but useful in my opinion. Your way is more correct but more complex.
BTW I dont use and dont like django forms at all.
Solved. I realized I wasn't using the create_user method I wrote in my registration view.
Updated the line below:
user = User.objects.create_user(email=email, city=city, province=province, password=password, first_name=first_name, last_name=last_name, phone_number=phone_number, age=age, gender=gender)
After this, my login form and validation worked. So for anyone having a similar issue, make sure you're using the create_user method if you wrote one/if you're using a custom user model/if you call user.set_password(password) in that method and not in your view.

Django login problems

I can register new user. But after logout, I cannot login again .It shows user does not exist. But when I checked admin panel I get hashed password.....
forms.py
class UserLoginForm(forms.Form):
email = forms.EmailField()
password = forms.CharField(widget=forms.PasswordInput)
def clean(self, *args, **kwargs):
email = self.cleaned_data.get("email")
password = self.cleaned_data.get("password")
if email and password:
user = authenticate(email=email, password=password)
if not user:
raise forms.ValidationError("User Does Not Exist.")
if not user.check_password(password):
raise forms.ValidationError("Password Does not Match.")
if not user.is_active:
raise forms.ValidationError("User is not Active.")
return super(UserLoginForm, self).clean(*args, **kwargs)
views.py
def login_view(request): # users will login with their Email & Password
if request.user.is_authenticated:
return redirect("/")
else:
title = "Login"
form = UserLoginForm(request.POST or None)
if form.is_valid():
email = form.cleaned_data.get("email")
password = form.cleaned_data.get("password")
# authenticates with Email & Password
user = authenticate(email=email, password=password)
login(request, user)
return redirect("/")
context = {"form": form,
"title": title
}
return render(request, "accounts/login.html", context)
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.CharField(max_length=500, null=True)
about = models.CharField(max_length=1000, null=True)
slogan = models.CharField(max_length=500, null=True)
def __str__(self):
return self.user.username
class Gig(models.Model):
CATEGORY_CHOICES = (
("GD", "Graphics & Design"),
("DM", "Digital & Marketing"),
("VA", "Video & Animation"),
("MA", "Music & Audio"),
("PT", "Programming & Tech")
)
title = models.CharField(max_length=500)
category = models.CharField(max_length=2, choices=CATEGORY_CHOICES)
description = models.CharField(max_length=1000)
price = models.IntegerField(default=6)
photo = models.FileField(upload_to='gigs')
status = models.BooleanField(default=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
create_time = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.title
class Purchase(models.Model):
gig = models.ForeignKey(Gig, on_delete=models.CASCADE)
buyer = models.ForeignKey(User, on_delete=models.CASCADE)
time = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.gig.title
class Review(models.Model):
gig = models.ForeignKey(Gig, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.CharField(max_length=500)
def __str__(self):
return self.content
I can register new user. But after logout, I cannot login again .It shows user does not exist. But when I checked admin panel I get hashed password.....
registration view.....
def register_view(request): # Creates a New Account & login New users
if request.user.is_authenticated:
return redirect("/")
else:
title = "Register"
form = UserRegistrationForm(request.POST or None, request.FILES or None)
if form.is_valid():
user = form.save(commit=False)
password = form.cleaned_data.get("password1")
user.set_password(password)
user.save()
prof = Profile(user=user)
prof.save()
authenticate(email=user.email, password=password)
login(request, user)
return redirect("/")
context = {"title": title, "form": form}
return render(request, "accounts/form.html", context)
def logout_view(request): # logs out the logged in users
if not request.user.is_authenticated:
return redirect("login")
else:
logout(request)
return redirect("/")

Django - How to run consecutive forms?

I have a user registration form that asks for user information and also asks a question: "Are you a PSMC member?"
The options are:
rank = [
('Supporter', 'Supporter (non-member)'),
('Anak', 'Anak'),
('Uso', 'Uso'),
('Chief', 'Chief'),
]
If Supporter is selected, then the registration form proceeds and saves user info, etc. This part works fine. However, if Anak is selected, I want it to take the user to another form that asks additional questions.
In my forms.py, I have class RegisterForm which is the main registration form for all users. I also have class AnakRegisterForm which is what I want it to continue on to. I used Django's AuthenticationForm based off what I read from their website (but I could be wrong). I know the issue is in views.py register function. Specifically:
if rank == 'Anak':
anak_register(response)
During my debug session, after it moves response to anak_register function, it gets a bunch of scrambled information. I'm pretty lost, any help would be appreciated. Here is my code:
forms.py
class RegisterForm(UserCreationForm):
email = forms.EmailField(
initial='',
required=True,
help_text='Please enter a valid email address'
)
rank = forms.ChoiceField(
label='Are you a PSMC member?',
choices=SavBlock.models.User.rank,
initial=False,
required=True,
help_text='Member accounts will be validated with your HC.'
)
class Meta:
model = User
# username = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
fields = ['username', 'first_name', 'last_name', 'email',
'rank', 'password1', 'password2']
def save(self, commit=True):
user = super(RegisterForm, self).save(commit=False)
user.email = self.cleaned_data['email']
user.ranking = self.cleaned_data['rank']
if commit:
user.save()
return user
class AnakRegisterForm(AuthenticationForm):
tribe = forms.ChoiceField(
label='What tribe are you from, Uce?',
choices=SavBlock.models.Anak.tribe,
initial=False,
required=True,
help_text='Member accounts will be validated with your HC.'
)
class Meta:
model = Anak
fields = ['tribe']
def save(self, commit=True):
user = super(AnakRegisterForm, self).save(commit=False)
user.tribe = self.cleaned_data['tribe']
if commit:
user.save()
return user
class UsoRegisterForm(AuthenticationForm):
pass
class ChiefRegisterForm(AuthenticationForm):
pass
views.py
def register(response):
context = {}
if response.method == "POST":
form = RegisterForm(response.POST)
if form.is_valid():
form.save()
rank = form.cleaned_data.get('rank')
if rank == 'Anak':
anak_register(response)
else:
form.save()
messages.success(response, 'Registration successful. Please login.')
return redirect('login')
else:
context['register'] = form
else:
form = RegisterForm()
context['register'] = form
return render(request=response, template_name='register/register.html', context={'form': form})
def anak_register(response):
# context = {}
if response.method == "POST":
form = AnakRegisterForm(response.POST)
if form.request.is_valid():
form.save()
messages.success(response, 'Registration successful. Please login.')
return redirect('login')
else:
'''
context['register'] = form
'''
else:
form = AnakRegisterForm()
# context['register'] = form
# messages.error(request, 'Unsuccessful registration. Invalid information.')
# form = RegisterForm
return render(request=response, template_name='register/register.html', context={'form': form})
models.py
class User(AbstractBaseUser, PermissionsMixin):
rank = [
('Supporter', 'Supporter (non-member)'),
('Anak', 'Anak'),
('Uso', 'Uso'),
('Chief', 'Chief'),
]
tribe = [
('NaKoaHema', 'Na Koa Hema'),
('Alakai', 'Alaka\'i')
]
username = models.CharField("user name", max_length=50, default='', unique=True)
email = models.EmailField("email address", max_length=30, unique=True, blank=True)
first_name = models.CharField("first name", max_length=50)
last_name = models.CharField("last name", max_length=50)
is_active = models.BooleanField('active', default=True)
# password = models.CharField("password", unique=True, max_length=32, default='')
id = models.AutoField(primary_key=True)
is_staff = models.BooleanField('staff status', default=False)
date_joined = models.DateField('date_joined', default=timezone.now)
ranking = models.CharField(choices=rank, max_length=50, default="Supporter")
objects = UserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email', 'password', 'ranking']
# Magic method returns string of self
def __str__(self):
return f"User {self.first_name} {self.last_name} rank {self.rank}".strip()
#property
def get_full_name(self):
return f"{self.first_name} {self.last_name}".strip()
class Anak(User):
def __init__(self, first_name, last_name, tribe):
super().__init__(first_name, last_name)
self.tribe = tribe.title()
self.rank = User.rank[1]
EDIT
I changed AuthenticationForm to UserCreationForm and now it accepts the form. However, when I try to run it, I get the following error:
TypeError at /register/
__init__() missing 1 required positional argument: 'tribe'
If someone could point me in the right direction, I'd appreciate it!
Not sure how I missed this, but the best solution that I found is to implement Django Form Wizard. More information can be found here:
https://django-formtools.readthedocs.io/en/latest/wizard.html

Suppress django signal

I have been struggling with this for a couple of weeks now and It seems, I can't get it to work.
As you sign up on my website, you are able to create a userprofile and a company. Then, you are able to add members to your company, however the signal just fires everytime and creates empty companies. How do I stop django from doing this?
model.py
class Companyname(models.Model):
company_name = models.CharField(max_length=100, default = '', null=True, blank=True)
user = models.OneToOneField(User, on_delete=models.CASCADE)
description = models.TextField(max_length=10000, default = '', null=True, blank=True)
def __str__(self):
return self.company_name
#receiver(post_save, sender=User)
def update_user_company(sender, instance, created, **kwargs):
if created:
Companyname.objects.create(user=instance)
if instance.companyname.company_name is '':
print("just print this")
else:
instance.companyname.save()
the company gets stored on the userprofile
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
description = models.CharField(max_length=100, default = '', null=True, blank=True)
company = models.ForeignKey(Companyname, null=True, on_delete=models.CASCADE)
role = models.ForeignKey(Role, null=True, on_delete=models.CASCADE)
team = models.ForeignKey(Team, null=True, on_delete=models.CASCADE)
company_admin = models.BooleanField(default=False)
add_user view.py
def add_user(request):
if request.method == 'POST':
form = AddUserForm(request.POST)
if form.is_valid():
company = request.user.userprofile.company_id
form.save()
user = form.save()
user.refresh_from_db()
user.userprofile.company_id = company
user.userprofile.role = form.cleaned_data.get('role')
user.is_active = False
user.save()
register view.py
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = form.save()
user.refresh_from_db() # load the profile instance created by the signal
user.userprofile.description = form.cleaned_data.get('description')
user.companyname.company_name = form.cleaned_data.get('company_name')
user.userprofile.company_id = user.companyname.id
user.save()
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=user.username, password=raw_password)
login(request, user)
return redirect('/account/my_product')
else:
form = RegistrationForm()
return render(request, 'accounts/reg_form.html', {'form': form})
Hope someone can help :)

Django UserCreationForm add request.user.pk ?

Hi i need add request user pk to UserCreationForm. I try many times, but with out results. In my dashboard i have user owner and i have user seller.
One model for all 3 types user. So Owner can create another user with role=seller, but for this i need add parent field with param=request.user.pk to seller
Custom UserModel
from django.db import models
from django.contrib.auth.models import AbstractUser
USER = 0
OWNER = 1
SELLER = 2
user_type_choice = (
(USER, 'User'),
(OWNER, 'Owner'),
(SELLER, 'Seller'),
)
class User(AbstractUser):
role = models.CharField(max_length=100, choices=user_type_choice, default=USER)
idn = models.CharField(max_length=10, blank=True, default=None, null=True)
mobile = models.CharField(max_length=15, blank=True, default=None, null=True)
parent = models.ForeignKey('self', null=True, blank=True)
tariff = models.IntegerField(default=None, null=True, blank=True)
class Meta(AbstractUser.Meta):
swappable = 'AUTH_USER_MODEL'
forms.py
class SellerRegisterForm(UserCreationForm):
email = forms.EmailField(required=True)
first_name = forms.CharField(required=False)
last_name = forms.CharField(required=False)
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2') """try add and remove 'parent' here in felds """
def save(self, commit=True):
user = super(SellerRegisterForm, self).save(commit=False)
user.email = self.cleaned_data['email']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.role = ROLE_SELLER
# try add user.parent = self.request.user.pk
# but it does not work
if commit:
user.save()
return user
views.py
def register_seller(request):
if request.method == 'POST':
form = SellerRegisterForm(request.POST) # create form object
if form.is_valid():
#try add new_form = form.save(commit=False)
# new_form.parent = request.user.pk
# new_form.save() but it not working
form.save()
return HttpResponseRedirect('/accounts/login')
else:
form = SellerRegisterForm()
return render(request, 'register_owner.html', {'form': form})
You need to pass the user object through the form's __init__ method.
class SellerRegisterForm(UserCreationForm):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
super(SellerRegisterForm, self).__init__(*args, **kwargs)
and in your view:
form = SellerRegisterForm(request.POST, user=request.user)
Then simply use self.user anywhere in your form class.

Categories