django foreign key relationships - python

models.py
class Hub(models.Model):
name = models.CharField(max_length=150)
def __str__(self):
return self.name
class User(AbstractUser):
is_client = models.BooleanField(default=False)
is_trainer = models.BooleanField(default=False)
username = models.CharField('username', max_length=150, unique=True)
email = models.EmailField(unique=True)
hub = models.ForeignKey(Hub, on_delete=models.CASCADE, blank=True, null=True)
hub_position = models.CharField(max_length=150, default="")
mentor = models.ForeignKey('self', on_delete=models.CASCADE, blank=True,null=True)
terms = models.BooleanField(blank=True, default=False)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email', 'terms']
def get_absolute_url(self):
return reverse('student:dashboard', kwargs={'pk': self.pk})
Confused on how to design the models here. Each User can belong to exactly one Hub.A hub has one leader, many excoms and many members ,all of them belongs to User .The hubs are added from the admin side.Leader can accept hub joining requests from excoms and members.

I'd add the user position as a choice field to the User, so you get a nice select box in the Admin.
class User(AbstractUser):
USER_POSITIONS = ((0, 'Regular'), (1, 'Leader'), (2, 'Excom'))
hub = models.ForeignKey(Hub, on_delete=models.CASCADE, blank=True, null=True)
hub_position = models.IntegerField(default=0, choices=USER_POSITIONS, ...)

Related

Django: How do I check if a User has already read/seen an article?

I am building a web-application for my senior design project with Python and Django. I have a user model that is able to read/write articles to display on the website. I have some tasks I want to accomplish.
I want to make it so that if an article is accessed (read) by a user, it is indicated for only that user that the article has been previously accessed. If I were to log into a brand new user account, the same article wouldn't be indicated as "accessed" for the new account.
How would I be able to present on the front-end side that the article has been viewed by the user logged in? (ie: make the article title bolded or a different color to indicate its been already visited)
Below are my models and views:
User model
class User(AbstractBaseUser, PermissionsMixin):
first_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=30, blank=True)
email = models.EmailField(unique=True, max_length=255, blank=False)
university = models.CharField(max_length=200, null=True, blank=True)
newsletter_subscriber = models.BooleanField(default=False)
is_email_verified = models.BooleanField(default=False)
is_staff = models.BooleanField(
default=False,
help_text=(
'Designates whether the user can log into '
'this admin site.'
),
)
is_active = models.BooleanField(
default=True,
help_text=(
'Designates whether this user should be '
'treated as active. Unselect this instead '
'of deleting accounts.'
),
)
date_joined = models.DateTimeField(default=timezone.now)
objects = UserManager()
USERNAME_FIELD = 'email'
def __str__(self):
return self.email
Article model
class Article(models.Model):
user = models.ForeignKey(
User, on_delete=models.DO_NOTHING, null=True, blank=True)
title = models.CharField(max_length=200, null=True, blank=False)
author = models.CharField(max_length=200, null=True, blank=False)
year = models.CharField(max_length=200, null=True, blank=False)
journal = models.CharField(max_length=200, null=True, blank=False)
description = models.TextField(null=True, blank=True)
URL = models.CharField(max_length=200, null=True, blank=False)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
class MetaData:
ordering = ['-created']
Article detail view
class ArticleDetail(LoginRequiredMixin, DetailView):
model = Article
context_object_name = 'articles'
template_name = 'home/article_detail.html'
Thank you!
You could create an extra table.
class ArticleSeenRecord(models.Model):
user = models.ForeignKey("django.contrib.auth.models.User", on_delete=models.CASCADE)
article = models.ForeignKey(Article, on_delete=models.CASCADE)
And then in your article view, create a new record when one doesn't exist, for that article combined with the authenticated user.
class ArticleDetail(LoginRequiredMixin, DetailView):
model = Article
context_object_name = 'articles'
template_name = 'home/article_detail.html'
def get_object(self, queryset=None):
obj = super().get_object(queryset)
record, created = ArticleSeenRecord.objects.get_or_create(user=self.request.user, article=obj)
return obj
class Article(models.Model):
...
def seen_by_user(self, user):
return self.atricleseenrecord_set.objects.filter(user=user).exists()
I added the extra function here. You will also need to add a template tag which you can ideally copy from this example
#register.simple_tag
def article_seen_by_user(article, user):
return article.seen_by_user(user)
For further guidance on how to use and register custom template tags, please refer to this page of the documentation:
https://docs.djangoproject.com/en/4.0/howto/custom-template-tags/
Specifically this section:
https://docs.djangoproject.com/en/4.0/howto/custom-template-tags/#django.template.Library.simple_tag

How to join 3 or more than 3 models in one single query ORM?

I am having 4 models linked with a foreign key,
class CustomUser(AbstractUser):
username = None
email = models.EmailField(('email address'), unique=True)
phone_no = models.CharField(max_length=255, unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = CustomUserManager()
def __str__(self):
return self.email
class personal_profile(models.Model):
custom_user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
picture = models.ImageField(default='profile_image/pro.png', upload_to='profile_image', blank=True)
role = models.CharField(max_length=255, blank=True, null=True)
gender = models.CharField(max_length=255, blank=True, null=True)
date_of_birth = models.DateField(blank=True, null=True)
def __str__(self):
return str(self.pk)
class academia_profile(models.Model):
custom_user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
education_or_certificate = models.CharField(max_length=255, blank=True, null=True)
university = models.CharField(max_length=255, blank=True, null=True)
def __str__(self):
return str(self.pk)
class contact_profile(models.Model):
custom_user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
country = models.CharField(max_length=255, blank=True, null=True)
state = models.CharField(max_length=255, blank=True, null=True)
city = models.CharField(max_length=255, blank=True, null=True)
def __str__(self):
return str(self.pk)
For extracting the data of those four models, I need to extract it by querying 4 times differently and then by passsing for different variables to HTML templates it something a hectic plus would be reducing the performance speed (I am sure!)
My current queries be like
user_base = CustomUser.objects.get(id=user_id)
user_personal = personal_profile.objects.get(custom_user=user_id)
academia = academia_profile.objects.get(custom_user=user_id)
contact = contact_profile.objects.get(custom_user=user_id)
Is it possible to get all of the four queries values in a single variable by hitting a single join query in ORM ?
also, I want to extract just the country from contact_profile and picture from personal_profile in the join query.
Select_related() can able to work here but how? that's what I am not getting.
You are looking for prefetch_related:
Returns a QuerySet that will automatically retrieve, in a single batch, related objects for each of the specified lookups.
user_base = (
CustomUser
.objects
.prefetch_related( #<-- THIS!
"personal_profile_set",
"academia_profile_set",
"contact_profile_set")
.get(id=user_id))
personal_profile = user_base.personal_profile_set.all()[0]
academia_profile = user_base.academia_profile_set.all()[0]
contact_profile = user_base.contact_profile_set.all()[0]
Btw, if you have only one personal_profile, academia_profile, contact_profile per CustomUser, consider changing ForeignKey by OneToOneField and use select_related.

Cannot assign "'1'": "Groups.profile" must be a "Profile" instance

I have Profile Model that have instance model user.. I am trying to create group using form. that group model have Profile model as instance, so how do I select authenticated user automatic to create group, I getting confused...
This is my Group Model
class Groups(models.Model):
profile = models.ForeignKey(Profile, related_name='my_groups', on_delete=models.CASCADE)
groups_name = models.CharField(max_length=150)
slug = models.SlugField(max_length=150, unique=True)
cover_pic = models.ImageField(upload_to='images/groups/', null=True, blank=True)
type_group = models.CharField(max_length=150)
created_date = models.DateTimeField(auto_now_add=True)
about_group = models.TextField(max_length=600)
members = models.ManyToManyField(Profile,through="GroupMember")
def __str__(self):
return self.groups_name
This is my profile Model
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
slug = models.SlugField(max_length=100, unique=True)
profile_pic = models.ImageField(upload_to='images/user/profile/', null=True, blank=True)
cover_pic = models.ImageField(upload_to='images/user/profile/', null=True, blank=True)
user_bio = models.TextField(null=True,blank=True, max_length=255)
designation = models.CharField(blank=True,null=True, max_length=255)
education = models.CharField(blank=True, null=True, max_length=255)
marital_status = models.CharField(blank=True, null=True, max_length=60)
hobbies = models.CharField(blank=True, null=True, max_length=500)
location = models.CharField(blank=True, null=True, max_length=500)
mobile = models.IntegerField(blank=True, null=True)
def __str__(self):
return str(self.user)
This is form for create group
class GroupCreateForm(forms.ModelForm):
class Meta:
model = Groups
fields = ('cover_pic', 'profile', 'groups_name', 'type_group', 'about_group')
profile = forms.CharField(widget=forms.TextInput(attrs={
'class': 'form-control input-group-text',
'value':'',
'id':'somesh',
'type': 'hidden',
}))
This is create group html file
this is html page
this is error..
You have set a CharField for profile in your form. When you send data to this form, it tries to make a Group record with a FK to a CharField for example "1" and this gives you error because you should pass Profile object to Group.
Depends on what exactly you want, there are some options.
You can use ModelChoiceField. Read about it in https://docs.djangoproject.com/en/3.2/ref/forms/fields/#django.forms.ModelChoiceField
Or you can use Inline FormSet and read about it in https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets
And an example for Inline FormSet in Creating a model and related models with Inline formsets

How to add specific permission view to certain users based on their field in Django?

So basically i have to make sure Users that are from the same department field to view and create any datas in the database. Not sure how to apply it using field-based user permissions?
class Profile(AbstractUser):
class Meta:
verbose_name_plural = 'Profiles'
company = models.CharField(max_length=30, null=True)
contact = models.CharField(max_length=20, null=True)
branch = models.ForeignKey('generals.Branch',
on_delete=models.CASCADE)
department = models.ForeignKey('generals.Department',
on_delete=models.CASCADE)
created_by = models.CharField(max_length=20)
modify_by = models.CharField(max_length=20)
modify_date = models.DateTimeField(default=datetime.now, blank=True)
is_active = models.BooleanField(default=False, null=True,
blank=True)
is_superuser = models.BooleanField(default=False, null=True,
blank=True)
is_staff = models.BooleanField(default=False, null=True,
blank=True)
def __str__(self):
return self.username
You should use what's already implemented in Django, and you'll gain a lot of time.
class Person(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
company = models.ForeignKey(Group, on_delete=models.CASCADE)
contact = models.ForeignKey('Person', on_delete=models.CASCADE)
branch = models.ForeignKey('generals.Branch',
on_delete=models.CASCADE)
department = models.ForeignKey('generals.Department',
on_delete=models.CASCADE)
created_by = models.ForeignKey('Person', on_delete=models.CASCADE)
modify_by = models.ForeignKey('Person', on_delete=models.CASCADE)
modify_date = models.DateTimeField(default=datetime.now, blank=True)
even though my eyes are burning because my syntax here is not PEP8 compliant, you should get the big picture: all the permissions are already handled by User and Group.
Just create a Group that has the name of the company, and give this group access (or not) to specific tables.

Get user instance from profile model __str__ in django

I have this simple model:
class Profile(models.Model):
bio = models.CharField(max_length=300, blank=False)
location = models.CharField(max_length=50, blank=
edu = models.CharField(max_length=250, blank=True, null=False)
profession = models.CharField(max_length=50, blank=True)
profile_image = models.ImageField(
upload_to=upload_image, blank=True, null=False)
def __str__(self):
try:
return str(self.pk)
except:
return ""
and a User model:
class User(AbstractBaseUser, UserTimeStamp):
first_name = models.CharField(max_length=50, blank=False, null=False)
email = models.EmailField(unique=True, blank=False, null=False)
profile = models.OneToOneField(Profile, on_delete=models.CASCADE)
uuid = models.UUIDField(
db_index=True,
default=uuid_lib.uuid4,
editable=False
)
is_admin = models.BooleanField(default=False, blank=False, null=False)
is_staff = models.BooleanField(default=False, blank=False, null=False)
is_active = models.BooleanField(default=True, blank=False, null=False)
objects = UserManager()
USERNAME_FIELD = "email"
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, perm_label):
return True
As you can see in User model I have a OneToOneField to Profile.
but in Profile model I can't access user instance to just use its email in str method. something like this:
def __str__(self):
return self.user.email
How can I do this? sometime these relations are confusing to me.
UPDATED
Yes self.user.email works well. but the problem is something else.
I have two type of users. users and teachers.
and each of them has field profile in their model. so if I say:
def __str__(self):
return self.user.email
It just returns email of user instances. what about teachers?
user model:
class User(AbstractBaseUser, UserTimeStamp):
profile = models.OneToOneField(Profile, on_delete=models.CASCADE, related_name='user_profile')
teacher model:
class Teacher(AbstractBaseUser, UserTimeStamp):
profile = models.OneToOneField(Profile, on_delete=models.CASCADE, related_name='teacher_profile')
profile model:
def __str__(self):
if hasattr(self, 'user_profile'):
# profile belong to user
print(self.user_profile.pk)
elif hasattr(self, 'teacher_profile'):
# profile belong to teacher
print(self.teacher_profile.pk)

Categories

Resources