My models:
class ClientProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, related_name='client_profile')
follows = models.ManyToManyField(User,
related_name='follows',blank=True)
profile_picture = models.ImageField( blank=True)
phone_regex = RegexValidator(
regex=r'^\+?1?\d{9,15}$',
message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed."
)
mobile_number = models.CharField(validators=[phone_regex],
max_length=17, blank=True)
dob = models.DateField(auto_now = False, null = True)
profile_summary = models.TextField()
my_career_objective = models.TextField()
educational_qualification = models.CharField(max_length=200)
work_experience = models.IntegerField(blank=True, null=True)
skill_set = models.TextField(blank=True)
address_1 = models.CharField(max_length=300,blank=True)
address_2 = models.CharField(max_length=300,blank=True)
# new fileds
about_me = models.TextField(blank=True)
birthplace = models.CharField(max_length=150,blank=True)
lives_in = models.CharField(max_length=150,blank=True)
occupation = models.CharField(max_length=150, blank=True)
gender = models.CharField(choices=GENDER_CHOICES,max_length=150, blank=True)
marital_status = models.CharField(choices=MARITAL_CHOICES,max_length=150, blank=True,default=1)
religion = models.CharField(max_length=150, blank=True)
political_incline = models.TextField(blank=True)
# other_social_networks = models.TextField(blank=True)
hobbies = models.TextField(blank=True)
favorite_tv_shows = models.TextField(blank=True)
favorite_movies = models.TextField(blank=True)
favorite_games = models.TextField(blank=True)
favorite_music_band_artists = models.TextField("Favorite Music, Bands / Artists", blank=True)
favorite_books = models.TextField(blank=True)
favorite_writers = models.TextField(blank=True)
other_interests = models.TextField(blank=True)
subscription = models.TextField(blank=True, null=True, default="Free")
def __str__(self):
return str(self.user.first_name) + " " + str(self.user.last_name)
class Task(models.Model):
level = models.ForeignKey(Level, on_delete=models.CASCADE)
todo = models.ForeignKey(ToDo, on_delete=models.CASCADE)
student = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=150)
content = models.TextField()
timestamp = models.TimeField(auto_now=True)
datestamp = models.DateField( auto_now=True)
like = models.ManyToManyField(User,related_name='user_likes',blank=True)
is_verified=models.BooleanField(default=False,blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('student:dashboard')
objects = PostManager()
#property
def comments(self):
instance = self
qs = Comment.objects.filter_by_instance(instance)
return qs
#property
def get_content_type(self):
instance = self
content_type =
ContentType.objects.get_for_model(instance.__class__)
return content_type
I want to display all tasks from logged in user and also all the tasks from all users followed by logged in user.What is the best django query to implement this? the follows field in the ClientProfile model is given as many to many field to depict all users followed by the user.How to write django query with 'or'.Each task points to a user through foreign key 'student' . I want to display all tasks from logged in user and all users followed by logged in user in the homepage
Put a related_name attribute in student field of Task. (let's call it task)
If logged_in_user is your logged in user object then logged_in_user.task would give task of logged_in_user and for user's followers tasks:
tasks = Task.objects.filter(student__in= logged_in_user.follows.all())
Without related_name.
task = Task.objects.filter(Q(student=logged_in_user) | Q(student__in=logged_in_user.follows.all()))
This worked for me :
client=ClientProfile.objects.get(user=request.user)
task = Task.objects.filter
(Q(student=request.user) |
Q(student__in=client.follows.all()))
.order_by('timestamp').prefetch_related('images_set')
Related
I want to update a field which is called level. My relation is like this. i am using django User model. Which is extended to Extended user like this below:-
class ExtendedUser(models.Model):
levels_fields = (
("NEW SELLER", "NEW SELLER"),
("LEVEL1", "LEVEL1"),
("LEVEL 2", "LEVEL 2"),
("LEVEL 3", "LEVEL 3")
)
user = models.OneToOneField(User, on_delete=models.CASCADE)
email = models.EmailField(null=True, unique=True)
contact_no = models.CharField(max_length=15, null=True)
profile_picture = models.ImageField(upload_to="images/", null=True)
country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True)
city = models.ForeignKey(City, on_delete=models.CASCADE, null=True)
level = models.CharField(max_length = 120, null=True, blank=True, choices=levels_fields, default="NEW SELLER")
I have a field call "Level" which is full of choices. Now i have a model named Checkout
This is the checkout model :-
class Checkout(models.Model):
ORDER_CHOICES = (
("ACTIVE", "ACTIVE"),
("LATE", "LATE"),
("DELIVERED", "DELIVERED"),
("CANCELLED", "CANCELLED"),
)
user = models.ForeignKey(User, on_delete=models.CASCADE)
seller = models.ForeignKey(
User, on_delete=models.CASCADE, null=True, related_name='seller')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now_add=True)
first_name = models.CharField(max_length=120)
last_name = models.CharField(max_length=120)
package = models.ForeignKey(OfferManager, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField(default=0)
price = models.DecimalField(decimal_places=2, max_digits=10, default=0.00)
total = models.DecimalField(decimal_places=2, max_digits=10, default=0.00)
grand_total = models.DecimalField(
decimal_places=2, max_digits=10, default=0.00, null=True)
paid = models.BooleanField(default=False)
due_date = models.DateField(null=True)
order_status = models.CharField(max_length=200, choices=ORDER_CHOICES, default="ACTIVE")
is_complete = models.BooleanField(default=False, null=True)
I have another model which is called SellerSubmit and the checkout is the foreign key here. Here is the model :-
class SellerSubmit(models.Model):
checkout = models.ForeignKey(Checkout, on_delete=models.CASCADE, related_name="checkout")
file_field = models.FileField(upload_to="files/", null=True)
submit_date = models.DateField(auto_now_add=True, null=True)
def __str__(self):
return str(self.id)
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
Now when a seller post in the SUbmitModel it will update the level to LEVEL1. How can do it,
This is what i tried :-
def sellerSubmitView(request, pk):
form = SellerSubmitForm()
if request.method == "POST":
file_field = request.FILES.get("file_field")
try:
checkout = Checkout.objects.get(id=pk)
# print(file_field)
except:
return redirect("manage-order")
else:
SellerSubmit.objects.create(checkout=checkout, file_field=file_field)
checkout.order_status ="DELIVERED"
chk = checkout.is_complete = True
l = Checkout.objects.filter(is_complete = True).filter(seller=request.user).count()
print("Count:" + str(l))
if l > 5:
out = checkout.seller.extendeduser.level = "LEVEL1"
print(out)
checkout.save()
print(chk)
checkout.save()
return redirect("manage-order")
args = {
"form": form,
"checkout_id": pk,
}
return render(request, "wasekPart/sellerSubmit.html", args)
checkout.seller.extendeduser.level = "LEVEL1"
checkout.seller.extendeduser.save()
This should solve your problem
out = checkout.seller.extendeduser.level = "LEVEL1"
print(out)
checkout.seller.extendeduser.save()
checkout.save()
It's my bad that didn't notice ExtendedUser is not extended from User.
Please let me know if it's worked or not
I am working on a django project. where there's two table one is developer table and another one is Jira table. developer table and jira table are connected with m2m relation.
here's my model.py
class developer(models.Model):
Developer_Name = models.CharField(max_length=100, unique=True)
Role = models.CharField(max_length=500)
Level = models.CharField(max_length=30)
Expertise = models.CharField(max_length=200)
Availability_Hours = models.CharField(max_length=500)
def __str__(self):
return self.Developer_Name
class jira(models.Model):
Jira_ID = models.CharField(max_length=100, blank=True)
Jira_Story = models.CharField(max_length=500)
Short_Description = models.CharField(max_length=500)
Story_Points = models.CharField(max_length=30)
Sprint = models.CharField(max_length=200)
DX4C_Object = models.CharField(max_length=500)
Developer = models.ManyToManyField(developer)
Sandbox = models.ForeignKey(environments, on_delete=models.CASCADE, limit_choices_to={'Mainline': None},blank=True, null=True)
def developer_assigned(self):
return ",".join([str(p) for p in self.Developer.all()])
Now my query is how to set a rule where if Dx4c object is changing then automatically one developer will assign based on the rule?
here's my view.py
def dependency_management(request):
jira_story = jira.objects.all()
return render(request, 'hello/Dependency_Management.html', {'JIRA': jira_story})
I want to make that dynamic. I mean if everytime I add any new DX4C object then without the code change that particular developer will assign based on the rule
Something like this:
class Developer(models.Model):
name = models.CharField(max_length=100, unique=True)
role = models.CharField(max_length=500)
level = models.CharField(max_length=30)
expertise = models.CharField(max_length=200)
availability_hours = models.CharField(max_length=500)
def __str__(self):
return self.name
class Jira(models.Model):
Jira_ID = models.CharField(max_length=100, blank=True)
story = models.CharField(max_length=500)
story_points = models.CharField(max_length=30)
sprint = models.CharField(max_length=200)
DX4C_Object = models.CharField(max_length=500)
developers = models.ManyToManyField(developer)
sandbox = models.ForeignKey(
environments,
on_delete=models.CASCADE,
limit_choices_to={'Mainline': None},
blank=True, null=True,
)
def developer_assigned(self):
return ",".join(self.developers.values_list('name', flat=True))
def save(self, *args, **kwargs):
if pk := getattr(self, 'id', 0):
old_value = self.__class__.objects.get(id=pk).DX4C_Object
super().save(*args, **kwargs)
if pk and self.DX4C_Object != old_value:
# do sth
I have three Models, in third models Foreign Key and ManyToMany fields are linked, which are:
Personal_info Models.py
class Personal_info(models.Model):
gen_choices = (
("पुरुष", "पुरूष"),
("महिला", "महिला"),
("तेस्रो", "तेस्रो"),
)
pinfo_id = models.AutoField(primary_key=True)
userid = models.OneToOneField(User, on_delete=models.CASCADE)
nfullname = models.CharField(validators=[max_len_check], max_length=128)
efullname = models.CharField(validators=[max_len_check], max_length=128)
dob_ad = models.DateField()
dob_bs = models.DateField()
gender = models.CharField(max_length=6, choices=gen_choices)
citizen_no = models.CharField(max_length=56)
cissue_dist = models.ForeignKey(District, on_delete=models.CASCADE)
cissue_date = models.DateField()
language = models.CharField(max_length=56)
p_district = models.CharField(max_length=56)
p_vdc = models.CharField(max_length=56)
p_ward = models.CharField(max_length=2)
p_city = models.CharField(max_length=56)
t_district = models.CharField(max_length=56)
t_vdc = models.CharField(max_length=59)
t_ward = models.CharField(max_length=2)
t_city = models.CharField(max_length=56)
telephone = models.BigIntegerField(null=True, blank=True)
mobile = models.BigIntegerField()
mother_name = models.CharField(validators=[max_len_check], max_length=128)
mother_cit = models.CharField(max_length=10, null=True)
father_name = models.CharField(validators=[max_len_check], max_length=128)
father_cit = models.CharField(max_length=10, null=True)
gfather_name = models.CharField(validators=[max_len_check], max_length=128)
gfather_cit = models.CharField(max_length=10, null=True)
spose_name = models.CharField(validators=[max_len_check], max_length=128, null=True)
spose_cit = models.CharField(max_length=10, null=True, blank=True)
image = models.FileField(upload_to="photos/", null=True, blank=True)
cit_image = models.FileField(upload_to="citizens/")
inclu_image = models.FileField(upload_to="inclusions/", null=True)
active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager
def __str__(self):
return str(self.efullname)
Educational Models.py
class Education(models.Model):
edu_id = models.AutoField(primary_key=True)
userid = models.ForeignKey(User, on_delete=models.CASCADE)
institute = models.CharField(max_length=255, validators=[max_len_check])
board = models.CharField(max_length=128, validators=[max_len_check1])
pexam = models.CharField(max_length=16, choices=exam_choices)
faculty = models.CharField(max_length=16, choices=fac_choices)
division = models.CharField(max_length=16, validators=[max_len_check2])
tmarks = models.IntegerField()
percent = models.FloatField(null=True, blank=True)
mainsub = models.CharField(max_length=16, validators=[max_len_check2])
image = models.FileField(upload_to="educations/", null=True, blank=True)
active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager
def __str__(self):
return str(self.userid)
V_applied models.py
class V_applied(models.Model):
appNo = models.IntegerField(null=True, blank=True, default=add_one)
p_srlno = models.IntegerField(blank=True, null=0, default=0)
userid = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Vacancy,on_delete=models.CASCADE)
inclusive = models.ManyToManyField(Inclusive)
bank = models.CharField(max_length=128)
v_no = models.CharField(max_length=32, validators=[max_len_check1])
dep_date = models.DateField()
ser_fee = models.IntegerField()
image = models.FileField(upload_to="vouchers/")
personal_info = models.ForeignKey(Personal_info, on_delete=models.CASCADE, blank=True)
education = models.ManyToManyField(Education, blank=True, default=0)
active = models.BooleanField(default=True)
status = models.CharField(max_length=10, validators=[max_len_check], default="Pending")
remarks = models.CharField(max_length=56, validators=[max_len_check1], default="Pending")
comment = models.CharField(max_length=128, validators=[max_len_check2], blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager
#property
def per_info(self):
return (self.personal_info.efullname, self.personal_info.gender, )
'''
def __str__(self):
return str(self.userid) + ':' + str(self.post)
Here I want to make auto save method in CreateView for ForeignKey & ManyToMany fields of V_applied models, for this I tried views.py as below:
#method_decorator(login_required(login_url='login'), name='dispatch')
class v_appliedadd(CreateView):
form_class = V_appliedForm
template_name = 'v_applied/v_applied_form.html'
success_url = '/v_applied/vapp_details/'
def form_valid(self, form):
form.instance.userid = self.request.user
form.instance.personal_info = Personal_info.objects.get(userid=self.request.user)
educationall = Education.objects.filter(userid=self.request.user)
for edu in educationall:
form.instance.education.add(edu)
return super().form_valid(form)
While saving data Error display like this:
ValueError at /v_applied/v_appliedadd/
"<V_applied: testuser>" needs to have a value for field "id" before this many-to-many relationship can be used.
Request Method: POST
Request URL: http://localhost:8000/v_applied/v_appliedadd/
Django Version: 3.0.8
Exception Type: ValueError
Exception Value:
"<V_applied: testuser>" needs to have a value for field "id" before this many-to-many relationship can be used.
Exception Location: C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\related_descriptors.py in __init__, line 846
Python Executable: C:\Users\User\AppData\Local\Programs\Python\Python38\python.exe
Python Version: 3.8.1
Python Path:
['D:\\DjangoProject\\app_epf',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\DLLs',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\lib',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38',
'C:\\Users\\User\\AppData\\Roaming\\Python\\Python38\\site-packages',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages']
Server time: Mon, 14 Sep 2020 23:09:21 +0545
I am new in python-django, please help me how to solve it.
form.instance.userid = self.request.user
form.instance.personal_info = Personal_info.objects.get(userid=self.request.user)
instance_from = form.save()
educationall = Education.objects.filter(userid=self.request.user)
for edu in educationall:
instance_edu = Education.objects.get(pk=edu.pk)
instance_from.education.add(instance_edu)
instance_from.save()
return super().form_valid(form)
I have made this function that runs every time a user logs in. I want to get the branch from 'user' but every time the session is set it's only available to the function even after setting it to BRANCH_ID in the settings file. any help? plus I don't want to do anything in view function with the request as it's not accessible from models
EDIT
I have added all the models
def perform_some_action_on_login(sender, request, user, **kwargs):
"""
A signal receiver which performs some actions for
the user logging in.
"""
request.session[settings.BRANCH_ID] = user.profile.branch_id
branch = request.session.get(settings.BRANCH_ID)
print(branch)
user_logged_in.connect(perform_some_action_on_login)
class WaybillTabularInlineAdmin(admin.TabularInline):
model = WaybillItem
extra = 0
# form = WaybillItemForm
fk_name = 'waybill'
autocomplete_fields = ('product',)
class WaybillAdmin(admin.ModelAdmin):
list_display = (
'from_branch',
'to_branch',
'updated_by',
)
list_filters = (
'from_branch',
'to_branch',
'product',
)
inlines = [WaybillTabularInlineAdmin]
readonly_fields = ("updated_by",)
what I was trying to do is products by the branch
class Waybill(models.Model):
from_branch = models.ForeignKey(
Branch,
default=1,
on_delete=models.CASCADE, related_name='from_branch')
to_branch = models.ForeignKey(
Branch, on_delete=models.CASCADE, related_name='to_branch')
comments = models.CharField(max_length=1024, blank=True)
created_date = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey(
User, on_delete=models.CASCADE,
blank=True, null=True,
related_name='waybill_created')
updated = models.BooleanField(default=False)
updated_by = models.ForeignKey(
User, on_delete=models.CASCADE, related_name='waybill_user')
def __str__(self):
return 'from {} to {}'.format(
self.from_branch.branch_name,
self.to_branch.branch_name,
)
class WaybillItem(models.Model):
waybill = models.ForeignKey(Waybill, on_delete=models.CASCADE)
product = models.ForeignKey(ProductDetail, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField()
def __str__(self):
return 'from {} to {}'.format(
self.waybill.from_branch,
self.waybill.to_branch
)
class Product(models.Model):
item = models.ForeignKey(
Item, on_delete=models.CASCADE, related_name="product")
branch = models.ForeignKey(
Branch, default=1, on_delete=models.CASCADE)
in_stock = models.BooleanField(default=True)
created_date = models.DateTimeField(auto_now_add=True)
updated_date = models.DateTimeField(auto_now=True)
objects = ProductManager()
class Meta:
verbose_name = "Inventory"
verbose_name_plural = "Inventories"
ordering = ("-created_date",)
constraints = [
models.UniqueConstraint(
fields=['item', 'branch'], name='unique product'),
]
def __str__(self):
return self.item.item_description
class ProductDetail(models.Model):
ITEM_CONDITION_CHOICES = (
("NEW", "New"),
("BROKEN", "Broken"),
("FAIRLY USED", "Fairly Used"),
)
condition = models.CharField(max_length=12, choices=ITEM_CONDITION_CHOICES,
default=ITEM_CONDITION_CHOICES[0][0])
product = models.ForeignKey(Product, on_delete=models.CASCADE)
short_description = models.CharField(max_length=255, blank=True)
color = models.CharField(max_length=15, blank=True)
bought_price = models.PositiveIntegerField(default=0.00)
sales_price = models.PositiveIntegerField(default=0.00)
retail_price = models.PositiveIntegerField(default=0.00)
item_code = models.CharField(max_length=15, default=0)
item_model_number = models.CharField(max_length=20, default=0)
quantity = models.PositiveIntegerField(default=0)
manufacturer_website = models.CharField(max_length=255, blank=True)
generated_url = models.CharField(max_length=255, blank=True)
created_date = models.DateTimeField(default=timezone.now)
updated_date = models.DateTimeField(auto_now=True)
# objects = ProductDetailManager()
i need to make Assign_manager field readonly for all users except for admin because he is the one who is assigning.
my models.py
class Manager(models.Model):
Manager_name = models.CharField(max_length=200)
Manager_id = models.IntegerField(default=0,primary_key=True)
Email_id = models.EmailField(max_length=20,blank=True)
def __unicode__(self):
return unicode(self.Manager_id)` class Manager(models.Model):
class Request(models.Model):
discussion_points = models.CharField(max_length=200)
Request_id = models.IntegerField(default=0,primary_key=True)
companies = models.CharField(max_length=200)
industry = models.CharField(max_length=200)
Functional_area= models.CharField(max_length=200)
Budget = models.IntegerField(default=0)
status = models.CharField(max_length=5, choices=STATUS_CHOICES, default='d')
Assign_manager =models.ForeignKey(Manager,blank=True,null=True)
Assign_executive= models.ForeignKey(Executive,null=True,on_delete=models.CASCADE,default='none',blank=True)
Rateperhour=models.IntegerField(blank=True,default=5,null=True)
linkedin_url = models.URLField(max_length=200, blank=True)