I have a model:
from django.contrib.auth.models import User
# Create your models here.
class Strategy(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
mod_date = models.DateTimeField(auto_now=True)
strategy_name = models.CharField(max_length=20)
strategy = models.TextField()
position = models.TextField()
I want to get username = "leo".
But in Strategy's user is using user_id.
How to get "models.Strategy.objects.get" or "models.Strategy.objects.filter" using username = "leo"?
Thank you.
Duplicated question Django models filter by foreignkey
Strategy.objects.filter(user__username='leo').first()
or
try:
Strategy.objects.get(user__username='leo')
except Strategy.DoesNotExists():
print 'username Leo does not exists'
Documentation
Related
I've inherited from the AbstractBaseUser as follows:
class User(AbstractBaseUser):
"""
Main User model, inherits from AbstractBaseUser
"""
# Meta
email = models.EmailField(verbose_name='email', max_length=60, unique=True)
username = models.CharField(max_length=40, unique=True) # equals to email
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
employee_of = models.OneToOneField(Customer, on_delete=models.SET_NULL, null=True)
So each User is linked to one and only one Customer.
Now within a view I want to access the instance of the current logged in user within the request object and get the employee_of value to get a queryset that contains all users of that customer.
def render_employees(request):
"""
Renders the employees page of the dashboard
:param request:
:return:
"""
# Return the value for the current site for css specific classes
dashboard_site = 'employees'
# Query the employees
qs_employees = User.objects.filter(employee_of=request.user.employee_of) # doesn't find field
...
However the filter doesn't work because request.user.employ_of doesn't seem to return anything. My IDE even suggests e.g. username, date_joined etc. but not employee_of.
Why's that?
class Customer(models.Model):
"""
A table that stores static data about a customer, usually a legal company
"""
legal_name = models.CharField(max_length=50)
street = models.CharField(max_length=30)
street_number = models.CharField(max_length=3)
def __str__(self):
return self.legal_name
Update:
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from applications.customer.models import Customer
from django.conf import settings
BaseUser = settings.AUTH_USER_MODEL
class User(AbstractBaseUser):
"""
Main User model, inherits from AbstractBaseUser
"""
# Relations
user = models.OneToOneField(BaseUser, related_name='user_profile', on_delete=models.CASCADE, null=True) # link to default user model
employee_of = models.OneToOneField(Customer, on_delete=models.SET_NULL, null=True, blank=True)
I linked the user to the default user model via Django admin. However in the view im still not able to access employee_of within request.user
It seems that request.user is a different model. It's User model from django.contrib.auth. https://docs.djangoproject.com/en/4.0/ref/contrib/auth/#django.contrib.auth.models.User.
What you can do about it?
In our app we have UserProfile model that have OnetoOne relation to django User.
You can then store employee_of value there.
class UserProfile(AbstractBaseUser):
user = models.OnetoOneField("auth.User", related_name="user_profile", on_delete=models.CASCADE)
employee_of = models.OneToOneField(Customer, on_delete=models.SET_NULL, null=True)
and then access request.user employees using something like
request.user.user_profile.employee_of
I'm working on a project in CS50w where I have to show the posts of the user I'm following and I'm getting the following error
ValueError: Cannot use QuerySet for "Following": Use a QuerySet for "User".
models.py:
class Post(models.Model):
"""Tracks all the posts"""
text = models.TextField(max_length=256)
user = models.ForeignKey(User, on_delete=models.CASCADE)
date_posted = models.DateTimeField(auto_now_add=True)
class Following(models.Model):
"""Tracks the following of a user"""
user = models.ForeignKey(User, on_delete=models.CASCADE)
following = models.ForeignKey(User, on_delete=models.CASCADE, related_name="followers")
And this how I'm trying to retrieve the posts of the users I'm following:
views.py
# Gets all the posts from the users the current user is following
followings_usernames = Following.objects.filter(user=request.user)
posts = Post.objects.filter(user=followings_usernames)
Any help is appreciated.
You can filter based on a field (Following.user) through a reverse relation (followers) through the Post.user field:
posts = Post.objects.filter(user__followers__user=request.user)
See the Django documentation for lookups that span relationships and the usage of double underscores to separate models and fields.
Try using this, it might help
# Gets all the posts from the users the current user is following
followings_usernames = list(Following.objects.filter(user=request.user).values_list('user', flat=True))
posts = Post.objects.filter(user__in=followings_usernames)
In My Django Project, there are two apps: Login and Company
The error that am receiving in this is
AttributeError: module 'login.models' has no attribute 'Country'
Company App > models.py
from django.db import models
from login import models as LM
class CompanyProfile(models.Model):
full_name = models.CharField(max_length=255,
unique = True)
country = models.ForeignKey(LM.Country,
on_delete=models.SET_NULL,
null=True,
blank=False)
state = models.ForeignKey(LM.State,
on_delete=models.SET_NULL,
null=True,
blank=False)
def __str__(self):
return self.full_name
Login App > models.py
class Country(models.Model):
"""List of Country"""
name = models.CharField(max_length=50, unique= True, default='None')
code = models.CharField(max_length=2, unique= True, primary_key=True, default ='NA')
def __str__(self):
return str(self.code)
class State(models.Model):
"""List fo State"""
region = models.CharField(max_length = 255, unique = True, primary_key=True, default='None')
country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True, blank=False, default ='NA')
def __str__(self):
return self.region
Here is test to check that weather is login is getting imported or not
def test_import():
try:
# import pdb; pdb.set_trace()
importlib.find_loader('LM.Country')
found = True
except ImportError:
found = False
print(found)
Answer is received stands to be True
python3 manage.py shell
>>> test_import()
True
Now on other stackoverflow blogs i checked i thought it could be of Circlular Import
But i have already fixed that still am getting this error?
Thanks in Advance
Regards
I am not able to see any issue here technically. Maybe Django doesn't support this alias way of mentioning model as Foreign Key which I have never tried this way.
But I would suggest to use string format for adding Foreign Key of other model as below.
class CompanyProfile(models.Model):
full_name = models.CharField(max_length=255, unique = True)
# In following line, as I mention model name in string which django understands
country = models.ForeignKey('login.Country', on_delete=models.SET_NULL,
null=True,blank=False)
Another way is simple import but it might be a problem in case of circular depedencies. So I don't recommend to use that.
I hope you get the answer out of it.
I am trying to iterate through all of my Task model objects and check whether they have employees attached to them. If they do have employees attached, then I want to cycle through the manytomany relation between projects and users and get each associated users email address. I am having difficulty accessing the email field. It keeps giving me 'not iterable' or "global name 'users__type' is not defined," depending on what I change. Am I missing something simple if my end result intended to be a string of user emails.
Models
from django.contrib.auth.models import User
from django.db import models
class CustomUser(models.Model):
user = models.OneToOneField(User, blank=True, null=True)
type = models.CharField(max_length=200, blank=True, null=True)
email = models.CharField(max_length=100, blank=True, null=True)
//Plus Other Custom User Fields//
class Task(models.Model):
users = models.ManyToManyField(CustomUser, blank=True, null=true)
//Plus Other Task Fields//
My other class
from django.models import Task
from django.models import CustomUser
from django.contrib.auth.models import User
def emailTaskList():
chosenPeople = []
notchosenPeople = []
chosenTask = Task.objects.filter(users__type = 'employee')
for e in chosen:
for d in e.users.all():
chosenPeople.append(d.email)
notchosenTask = Task.objects.filter(users__type != 'employee')
for a in notchosen:
for b in a.users.all():
notchosenPeople.append(b.email)
test = ' '.join(chosenPeople)
connection = mail.get_connection()
email = mail.EmailMessage('You have been assigned', test, [WebsiteEmail], [testRecipient])
email.send()
connection.close()
return
Thanks
Use the exclude() method instead of != comparison:
notchosen = Task.objects.exclude(users__type='employee')
I'm a new Django (1.3) user and I'm setting up the typical blog/article application. I have a model in which I'd like to save the current username (to see who created the article). I've implemented advice on this, but my code crashes the server with the message: "NameError: name 'User' is not defined". Here's my model:
from django.db import models
class Resort(models.Model):
name = models.CharField(max_length=300)
description = models.TextField()
location = models.CharField(max_length=300)
ski_hire = models.TextField()
weather = models.TextField()
piste_map = models.TextField()
webcam = models.TextField()
snow = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
author = models.ForeignKey(User)
def __unicode__(self):
return self.name
I have a sneaking suspicion that I need to override the save method in admin.py, but I'm not sure how to do this. Any advice would be greatly appreciated. Thanks!
You need to make sure you import user from django.contrib.auth.models in your models.py when using User in a foreign key.
In your admin.py you can use save_model:
class ResortAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
obj.author = request.user
obj.save()
Maybe You should import User class before assignment?
from django.contrib.auth.models import User