Requiring checking checkbox during in custom Django sign-up form - django

Im preparing customized Django registration form. I need adding two checkboxes that are required (RODO consent and consent for using images). How to declare in Django that this checkboxes must be checked before form could be send? Form is based on model and it looks like this:
Models.py
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True)
first_name = models.CharField(_('first name'),max_length=50)
last_name = models.CharField(_('last name'),max_length=150)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
RODO_consent = models.BooleanField(default=False)
image_consent = models.BooleanField(default=False)
marketing_consent = models.BooleanField(default=False)
date_joined = models.DateTimeField(default=timezone.now)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = CustomUserManager()
def __str__(self):
return self.email
Forms.py
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = CustomUser
fields = ('email','password1','first_name','last_name','RODO_consent','image_consent','marketing_consent')

You can add custom validation in your CustomUserCreationForm. field_names would be your RODO_consent and image_consent
def clean_field_name(self, field_name):
is_filled = self.cleaned_data.get(field_name)
if not is_filled:
raise forms.ValidationError('This field is required')
return is_filled

Related

Django type object 'Account' has no attribute 'USERNAME_FIELD' django

i tried to adding username=None didnt work
Account model is for auth
other models that are diffrent languge are just profile pic or date joined nothing important to the error i imagine
models.py
class Account(AbstractBaseUser):
email= models.EmailField(verbose_name='ایمیل', max_length=60, unique=True)
username = models.CharField(max_length=255, unique=True)
مسکن = models.CharField(max_length=255)
تاریخ_ثبت_نام = models.DateTimeField(verbose_name='تاریخ_ثبت_نام', auto_now_add=True)
اخرین_ورود = models.DateTimeField(verbose_name='اخرین_ورود', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
عکس_پروفایل = models.ImageField(max_length=255 ,upload_to=get_profile_image_filepath,null=True ,blank=True, default=get_default_profile_image)
objects = MyAccountManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
def __str__(self):
return self.username
def get_profile_image_filenames(self):
return str(self.عکس_پروفایل)[str(self.عکس_پروفایل).index(f'uploads/{self.pk})/'):]
def has_perm(self,perm, obj=None):
return self.is_admin
def has_module_perm(self , applabel):
return True

Django 4.0 - Trying to run a query based on result from another query

guys!
Here's what I'm trying to do:
I have a User model, a LinkedOrganization model, an Organization model that looks like this:
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(db_index=True, unique=True)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
mobile = models.CharField(max_length=12)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_superuser = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name', 'mobile']
class Meta:
verbose_name = 'User'
verbose_name_plural = 'Users'
# Organization fields
class Organization(models.Model):
organization_name = models.CharField(max_length=50, unique=True)
def __str__(self):
return self.organization_name
class LinkedOrganization(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='linked_user')
organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name='linked_organization')
is_manager = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
class Meta:
unique_together = (
("user", "organization")
)
In my API-view I'm trying to return all the users that are linked to an organization that the requester is a manager of.
Now, one requester can be a manager of 1 or more organizations, and I need to get all the users linked to those organizations. Meaning I need it to be sort of 'is member of organization A' OR 'is member of organization B', and iterate through all the organizations. Is it possible to do this with a Queryset in Django?
I realized when I wrote this that I could just get the organizations and use ReverseObjectManager to get the users of the organizations and iterate through those and make the dictionaries I need in Python, but if getting a query and use the result in a queryset is a function of Django that would be easier.
You may benefit from a slightly different database schema, not just for this query but in general. Consider the following:
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(db_index=True, unique=True)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
mobile = models.CharField(max_length=12)
organization = models.ForeignKey('Organization', on_delete=models.CASCADE, related_name='user_organization')
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_superuser = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name', 'mobile']
class Meta:
verbose_name = 'User'
verbose_name_plural = 'Users'
# Organization fields
class Organization(models.Model):
organization_name = models.CharField(max_length=50, unique=True)
manager = models.ForeignKey(User, etc...)
def __str__(self):
return self.organization_name
In this scenario, every user has an organization, and every organization has a manager. Simple. Also note that I referenced the 'Organization' in the foreign key field as a string, since it is declared above where the Organization model is defined. With that, you can query like so:
managed_users = User.objects.filter(user_organization__manager=request.user)
A common practice is to create a profile model for the user, where additional fields like their organization, contact info, etc can be added. In that case you'd have something like this:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
organization = models.ForeignKey(Organization, etc...)

use django-guardian with Custom User

I use custom user And i want to django-guardian to handle the permissions and groups. How i can do that
my user:
class ProfileUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(default=timezone.now)
username = models.CharField(max_length=255,unique=True)
first_name=models.CharField(max_length=255)
last_name= models.CharField(max_length=255)
departement= models.CharField(max_length=255)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = []
Just add a OneToOne field in the ProfileUser model that points to an actual user or use any other method included in the django documentation about extending the user model.

Querying Parent from the foreign key django

I have the following models :
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True)
first_name = models.CharField(max_length=32)
last_name = models.CharField(max_length=32)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(default=timezone.now)
USERNAME_FIELD = 'email' # unique identifier, changed to email (default was username)
REQUIRED_FIELDS = ['first_name', 'last_name']
objects = CustomUserManager() # custom manager for interacting with database
def __str__(self):
return self.email
class Refer(models.Model) :
referred_by = models.ForeignKey(CustomUser, on_delete=models.CASCADE, default='admin', related_name='referred_by')
referrals = models.ManyToManyField(CustomUser, related_name='referrals', blank=True)
unique_ref_id = models.CharField(max_length=8, blank=True, default=generate())
def __str__(self) :
return f'Referred By: {self.referred_by}'
I want to implement referral system using this, I have unique_for_id field (example 'exbvagtl'), how can i create new referral under that user?
Something like : Refer.objects.create(referred_by= CustomUser.objects.get(Refer__unique_ref_id='exbvagtl'))
Better model designs, resources and improvements are heavily welcomed!
I think you are overcomplicating things. By making a Refer object that has a ForeignKey to CustomUser, this means that each CustomUser can have zero, one or more Refer objects. While that is not impossible to manage, it makes it harder, since now your views will need to make sure you are working with the correct Refer object, or have to "concatenate" these. Furthermore it means that a CustomUser can have multiple unique_ref_ids.
The question is why we need such object in the first place. You can simply construct a unique_ref_id on the CustomUser object, and add a ForeignKey to 'self' that specifies what the referring person was:
class CustomUser(PermissionsMixin, AbstractBaseUser):
email = models.EmailField(unique=True)
first_name = models.CharField(max_length=32)
last_name = models.CharField(max_length=32)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(auto_now_add=True)
unique_ref_id = models.CharField(max_length=8, blank=True, default=generate)
referred_by = models.ForeignKey(
'self',
related_name='referrals',
null=True,
default=None,
on_delete=models.SET_NULL
)
USERNAME_FIELD = 'email' # unique identifier, changed to email (default was username)
REQUIRED_FIELDS = ['first_name', 'last_name']
objects = CustomUserManager() # custom manager for interacting with database
def __str__(self):
return self.email
Here we thus can add a user that was referred to by another user with:
CustomUser.objects.create(referred_by_id=id_of_referred_user)
If later the referred_by user is removed, then it will be set to NULL.
You can also query the users that have been referred by a user with:
myuser.referrals.all()
The problem is coming from your design of the referral system. Usually, in a referral system, one user has one referral_id. But your design suggests that one user can have multiple referral_ids.
I will suggest you move the unique_ref_id to the CustomUser model. That way you can do something like this:
Refer.objects.create(referred_by=CustomUser.objects.get(unique_ref_id="exbvagtl"))
2nd suggestion: put everything in one table
You will notice that the person referring another person is also a person, so it's basically a reference to self. In that regards you can have your CustomUser model look as follows:
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True)
first_name = models.CharField(max_length=32)
last_name = models.CharField(max_length=32)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(default=timezone.now)
referred_by = models.ForeignKey(self, on_delete=models.SET_NULL, blank=True, null=True)
unique_ref_id = models.CharField(max_length=8, blank=True, default=generate())
USERNAME_FIELD = 'email' # unique identifier, changed to email (default was username)
REQUIRED_FIELDS = ['first_name', 'last_name']
objects = CustomUserManager() # custom manager for interacting with database
def __str__(self):
return self.email
Base on that, you can do things like this:
Create a new user:
sponsor = CustomUser.objects.get(unique_ref_id="exbvagtl")
user = CustomUser(email=email, first_name=first_name, last_name=last_name,referred_by=sponsor)
user.save()
Get the list of a user's referrals:
sponsor = CustomUser.objects.get(unique_ref_id="exbvagtl")
referrals = CustomUser.objects.filter(referred_by=sponsor)
Hope this helps, if you have any doubts, don't hesitate to ask below.

Trying to serialize data from multiple models

I am trying to serialize three django models in a section of my api, but it seems he doesn't like the way I do it .. Im following the documentation of https://www.django-rest-framework.org/api-guide/relations/#nested-relationships
I have tried to create 3 serializers one for each model and then put everything together in the fields of the last
serializers.py
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ['name', 'user']
class UserCompanySerializer(serializers.ModelSerializer):
class Meta:
model = UserCompany
fields = ['name']
class UserInfoSerializer(serializers.ModelSerializer):
profile = UserProfileSerializer
companys = UserCompanySerializer(many=True)
class Meta:
model = CustomUser
fields = ['email', 'profile', 'companys']
I thought it would work but it returns the error:
ImproperlyConfigured at /user_info
Field name profile is not valid for model CustomUser.
models.py
class UserCompany(models.Model):
name = models.CharField(max_length=150, unique=True)
def __str__(self):
return self.name
class CustomUser(AbstractUser):
username = None
email = models.EmailField(_('email address'), unique=True)
is_active = models.BooleanField(default=False)
companys = models.ForeignKey(UserCompany, on_delete=models.CASCADE, null=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = CustomUserManager()
def __str__(self):
return self.email
class UserProfile(models.Model):
name = models.CharField(max_length=300, unique=True)
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
def __str__(self):
return self.name