Associating users with models django - python

I have a lot of models in model.py -
class Portfolio(models.Model):
company = models.TextField(null=True)
volume = models.IntegerField(blank=True)
date = models.DateField(null=True)
isin = models.TextField(null=True)
class Endday(models.Model):
company = models.TextField(null=True)
isin = models.TextField(null=True)
eop = models.TextField(max_length=100000)
class Results(models.Model):
companies = models.TextField(default=0)
dates = models.DateField(auto_now_add=False)
eodp = models.FloatField(null=True)
volume = models.IntegerField(null=True)
class Sectors(models.Model):
sector_mc = models.TextField(null=True)
class Insector(models.Model):
foundation = models.ForeignKey(Sectors, null=True)
name = models.TextField(null=True)
value = models.FloatField(default=0)
class AreaLineChart(models.Model):
foundation = models.ForeignKey(CompanyForLineCharts, null=True)
date = models.DateField(auto_now_add=False)
price = models.FloatField(null=True)
class Meta:
ordering = ['date']
I have more such models but as you can see from this snippet, they are not in any way related to any user.
Now I want to relate them to a particular user. In the views too, I was not classifying data per user in any way.
I make users from django admin with username and password and also generate a token for those users from admin. I can authenticate via username and password but from there I know I'd need to use permissions but how is what I do not know. Also, I have serializers that are associated to these models, I know I'd have to use permissions there too but again, I don't know how to. As much as I understand it has to be in someway like this-
#api_view(['GET'])
def searched_company_ohlc(request):
if request.method == 'GET':
// User.objects.get('username'=some_user)
//I guess.
qs = SearchedCompanyOHLC.objects.all()
serializer = SearchedCompanyOHLCSerializer(qs, many=True)
return Response(serializer.data)
Also, I'm using angularJS at the front-end that POSTS username and password on a view with POST decorator to verify the credentials. Where to go from here?

in your models.py you can relate user like this for example
from django.contrib.auth.models import User, Group
class Portfolio(models.Model):
owner = models.ForeignKey(User,verbose_name = 'User',related_name='portfolios')
company = models.TextField(null=True)
volume = models.IntegerField(blank=True)
date = models.DateField(null=True)
isin = models.TextField(null=True)

This has nothing to do with permissions.
If you want to associate your model with a user, use a ForeignKey to the user model.

Related

Django ManytoMany field remains empty after .add() method called

I'm using django to create a signup platform where students can signup to weekly classes.
Each class is a django model called ClassCards which has a ManytoMany relation to User model called signed_up_student that represents all the users signed up for that class as seen below
class ClassCards(models.Model):
content = models.CharField(max_length=100, default = '')
date = models.DateField(blank=True, null = True)
time = models.TimeField(blank=True,null=True)
signed_up_students = models.ManyToManyField(User,blank=True)
full = models.BooleanField(default = False)
max_students = models.IntegerField(default=4)
teacher = models.CharField(max_length=100, default='Adi')
I would like to add a subscription option that will automatically sign up subscribed students to this weeks class. Here is my Subscription model:
class Subscriptions(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null =True)
day = models.CharField(max_length=100, choices=day_choices, null=True)
time = models.TimeField(blank=True, null=True)
num_of_times_used = models.IntegerField(default=0)
cap = models.IntegerField(default=52)
active = models.BooleanField(default= True)
expirey_date = models.DateField()
date_created = models.DateField(default = timezone.now)
To accomplish this I have created a post_save signal:
#receiver(post_save,sender=ClassCards)
def apply_subsciptions(sender,instance,created, **kwargs):
if created:
subs = Subscriptions.objects.filter(day=instance.date.strftime("%A"),
time=instance.time)
for s in subs:
instance.signed_up_students.add(s.user)
print(instance.signed_up_students.get())
The code runs properly when a ClassCards is saved without throwing any errors and the print statement prints the relevant User However when I look on the admin page, I see that there are no users in the signed_up_students field.
I Would like to understand why this isn't working as desired which should adding that user to the ManytoMany field and what is the best practice for automatically updated a ManytoMany fields.
a little modification to the class ClassCards
class ClassCards(models.Model):
signed_up_students = models.ManyToManyField(User, symmetrical=False, related_name="student_cards_students_has", blank=True)
def signed_students_list(self):
return self.signed_up_students.all()
def cards_asigned_to_student_list(self):
return self.student_cards_students_has.all()
def assign_student(self, user):
self.signed_up_students.add(user)
def unsign_user(self, user):
self.signed_up_students.remove(user)
now in the signals
#receiver(post_save,sender=ClassCards)
def apply_subsciptions(sender,instance,created, **kwargs):
if created:
subs = Subscriptions.objects.filter(day=instance.date.strftime("%A"),time=instance.time)
for s in subs:
instance.assign_student(s.user)
instance.save()
print(instance.signed_students_list())
print(instance.cards_asigned_to_student_list())

Django user model (Employee and Customer)

I am currently working on a mobile app delivery system which involves two types of users: "Employee" and "Customer". Each type of user would have different views and permissions within the app. In addition, each type of user would their own "profile", if you will. The employee's profile purpose is mostly just to designate company roles. The customer's profile is mostly used to save an address for delivery.
I am trying to get some opinions on what the best practice to achieve something like this would be. I can't decide if its better to use AbstractBaseUser or AbstractUser.
Below is a visual of the models I want to create along with their relationship:
Below is the the user/models.py file that I mocked up:
class User(AbstractBaseUser):
USER_TYPES = (
('Employee', 'employee'),
('Customer', 'customer')
)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
email = models.EmailField()
phone_number = models.CharField(max_length=20)
user_type = models.CharField(max_length=8, choices=USER_TYPES)
def __str__(self):
return f'{self.first_name} {self.last_name}'
# if user.user_type == 'Employee'
class EmployeeProfile(models.Model):
EMPLOYEE_ROLES = (
('Driver', 'driver'),
('Production', 'production'),
('Manager', 'manger')
)
user = models.OneToOneField(User, on_delete=models.CASCADE)
role = models.CharField(max_length=12, choices=EMPLOYEE_ROLES)
def __str__(self):
return self.user
# if user.user_type == 'Customer'
class CustomerProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
company = models.CharField(max_length=100)
address = models.CharField(max_length=100)
address_2 = models.CharField(max_length=100)
city = models.CharField(max_length=50)
state = models.CharField(max_length=2, help_text="State Abbreviation (ex: OH)")
zipcode = models.CharField(max_length=5)
def __str__(self):
return self.user
I know that I would also need to use Django signals or something similar to create a User profile (for either an employee or customer, on user creation).
Your code works
But according to the design pattern standards, it can be said to put a Boolianfield in the user named is_employee and all the information of both types of users should be in AbstractUser, but with null=True and blank=True values.
This way you have a single user with which it can be separated by a is_employee field
I hope it was useful

How can I filter related field in django?

Say I have the model User which has a many-to-many relation with the model Company; and the model UserType, which is connected to both User and Company. Like this:
class User(models.Model):
name = models.TextField()
class Company(models.Model):
name = models.TextField()
users = models.ManyToManyField(User, related_name="companies")
class UserType(models.Model):
name = models.TextField()
company = models.ForeignKey(Company, related_name="user_types")
users = models.ManyToManyField(User, related_name="user_types")
I wanna find all Users in a Company, which is simple enough: User.objects.filter(companies=some_company). However, I also wanna filter the user_types field on the returned users objects, so that only UserType objects connected to the given Company is returned. To explain it with code, this should return true:
def check_user_types(users, company):
for user in users:
for user_type in user.user_types:
if user_type.company != company:
return false
return true
How would I do this?
I figured it out. For anyone facing the same problem, this solved it:
from django.db.models import Prefetch
users = User.objects.filter(companies=company).prefetch_related(
Prefetch(
"user_types",
queryset=UserType.objects.filter(company=company),
)
)

How to list objects with relationship manytomany on Django? example: users and follows

I was make a microblogging like twitter and I want to list the posts of users that authenticated user is following.
Models:
class Post(models.Model):
post = models.TextField(max_length=300)
created = models.DateTimeField(auto_now=True)
user = models.ForeignKey(User)
def __unicode__(self):
return self.post
class UserProfile(models.Model):
USER_SEX = (
('M', 'Masculino'),
('F', 'Femenino'),
)
birthday = models.DateField(null=False)
sex = models.CharField(max_length=1, choices=USER_SEX)
description = models.TextField(max_length=100, null=True)
location = models.CharField(blank=True, max_length=100, null=True)
user = models.OneToOneField(User)
follows = models.ManyToManyField('UserProfile', related_name='followed_by', blank=True, symmetrical=False)
def __unicode__(self):
return self.user.get_username()
Views:
def show_posts(request):
user = request.user
following = user.userprofile.follows.all()
posts = Post.objects.filter(user__in=following).order_by('-created')
return render_to_response("posts.html", context_instance = RequestContext(request, {'posts':posts}))
This function return all posts of all users, except the authenticated user. I don't want this.
I want to show all posts of users ONLY the user authenticated is following and also the posts of the user authenticated.
Someone can help me?
I'm not sure of my answer, but nobody answered, so here's my try.
following is a QuerySet, which becomes a list of UserProfile, but you filter on user__in, which is a list of User. Can you try making follows a ManyToManyField to User instead and tell us the results? Even if you still have the same problem, the filter will make more sense!

Django REST - Custom Serializer for Full Username

I have an application with Django/Django-REST on the backend with Angular on the front-end. I am looking for the correct way to convert a user ID to a full username for display in an Angular JS modal.
Here is my serializer:
from rest_framework import serializers
from .models import ArtnetTasks
from django.contrib.auth.models import User
class TaskSerializer(serializers.ModelSerializer):
date_assigned = serializers.DateTimeField(format='%Y-%m-%d')
assigned_by_name = serializers.SerializerMethodField('full_username')
assigned_to_name = serializers.SerializerMethodField('full_username')
def full_username(self, id):
user = User.objects.get(id=id)
name = user.first_name + " " + user.last_name
return name
class Meta:
model = ArtnetTasks, Users
fields = ('id', 'headline', 'message', 'assigned_to', 'assigned_to_name', 'assigned_by', 'assigned_by_name', 'date_assigned', )
My Model:
class ArtnetTasks(models.Model):
id = models.IntegerField(primary_key=True)
headline = models.CharField(max_length=75L)
message = models.TextField()
response_message = models.TextField(blank=True)
assigned_to = models.IntegerField(null=True, blank=True)
assigned_by = models.IntegerField(null=True, blank=True)
date_assigned = models.DateTimeField()
date_completed = models.DateTimeField(null=True, blank=True)
is_active = models.IntegerField(null=True, blank=True)
date_updated = models.DateTimeField(null=True, blank=True)
class Meta:
db_table = 'artnet_tasks'
assigned_to and assigned_by are user_id's that correspond with auth_user
It is throwing the following error then promptly breaking the Angular AJAX calls, the error from what I can tell is "argument must be a string or a number\054 not 'dict'"
This is my first project using both Django-REST and Angular and am sure I am missing something obvious.
Thanks in advance!
So, you can not set more than one model on your serializer. Your serializer can only handle one model per time. Another thing, the SerializerMethodField has as parameter self and obj, where, obj is your ArtnetTasks instance. As a better RESTful practice, I recommend you the follow example, if your user is authenticated:
class TaskSerializer(serializers.ModelSerializer):
date_assigned = serializers.DateTimeField(format='%Y-%m-%d')
assigned_by_name = serializers.SerializerMethodField('get_user_full_name')
assigned_to_name = serializers.SerializerMethodField('get_user_full_name')
def get_user_full_name(self, obj):
request = self.context['request']
user = request.user
name = user.first_name + " " + user.last_name
return name
class Meta:
model = ArtnetTasks
fields = ('id', 'headline', 'message', 'assigned_to', 'assigned_to_name', 'assigned_by', 'assigned_by_name', 'date_assigned', )
Better than this, I recommend you to create a simple serializer to the User model, and then , instead to use assigned_by_name and assigned_to_name, you can use:
user = YourUserSerialuzer()
But you will need a relation between User and ArtnetTasks model to do that.
You can see more examples of how do this, here: http://www.django-rest-framework.org/api-guide/relations

Categories