Django: how to upload media files to different folders? - python

I want to save file in automatically created folder related with Employee id_number like:
media->employee->attachments->emp001->emp001.pdf
models.py
from django.db import models
class Employee(models.Model):
id_number = models.CharField(primary_key=True, null=False, blank=False, unique=True, max_length=15)
full_name = models.CharField(max_length=255, null=False, blank=False)
name_with_initials = models.CharField(max_length=255, null=False, blank=False)
surname = models.CharField(max_length=255, null=False, blank=False)
phone = models.CharField(max_length=15, null=False, blank=False)
dob = models.DateField(null=False, blank=False)
gender = models.CharField(max_length=10, null=False, blank=False)
email = models.EmailField()
address = models.CharField(max_length=255, null=False, blank=False)
class EmployeeAttachments(models.Model):
employee = models.ForeignKey(Employee, on_delete=models.CASCADE)
cv = models.FileField(upload_to=f'employee/attachments/', max_length=100)
can any one tell me how to do this in django, django-rest-framework

This will change a path of cv on EmployeeAttachments according to your Employee id
def facility_path(instance, filename):
return f'attachments/employee/emp{instance.employee.id}/emp{instance.employee.id}.pdf'
class EmployeeAttachments(models.Model):
employee = models.ForeignKey(Employee, on_delete=models.CASCADE)
cv = models.FileField(upload_to=facility_path, max_length=500)

Related

How do I attach the user's order to the product issued Django

Ok, so I have this application where the users make an order for a Category through the app. Every category contains products. And what I want to do is when a product is issued to the user the order status for the order made by the user should change from 1(approved) to 4(issued) and the product name should be added in the order table to confirm the product that was issued to that request.
How do I do that in Django? Below are my models
class Category(models.Model):
name = models.CharField(max_length=50, blank=True, null=True)
timestamp = models.DateTimeField(auto_now_add=False, auto_now=True, null=True)
class Product(models.Model):
pro_name = models.CharField(max_length=100, blank=True, null=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True)
issue_to = models.ForeignKey('Order',default='', on_delete=models.CASCADE,blank=True, null=True)
serial_num = models.CharField(max_length=100, blank=True, null=True)
model_num = models.CharField(max_length=100, blank=True, null=True)
storage_size = models.CharField(max_length=50, blank=True, null=True)
memory_size = models.CharField(max_length=50, blank=True, null=True)
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, blank=True, null=True)
receive_quantity = models.IntegerField(default='0', blank=True, null=True)
issue_quantity = models.IntegerField(default='0', blank=True, null=True)
issue_by = models.CharField(max_length=50, blank=True, null=True)
last_updated = models.DateTimeField(auto_now_add=False, auto_now=False, null=True)
timestamp = models.DateTimeField(auto_now_add=False, auto_now=True, null=True)
class Order(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True)
pro_name = models.ForeignKey(Product, on_delete=models.CASCADE, null=True,related_name='product')
staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
order_quantity = models.PositiveIntegerField(null=True)
department = models.CharField(max_length=50, choices=DEPARTMENT, null=True)
order_status = models.IntegerField(default=0)
approve_quantity = models.IntegerField(default='1', blank=True, null=True)
transaction_id = models.CharField(default=uuid.uuid4().hex[:8].upper(), max_length=50, editable=False)
timestamp = models.DateTimeField(auto_now_add=False, auto_now=True, null=True)
Currently what I do is after a particular product has been issued to a user I have to go to the order table and change the order status to 4(issued) which is hectic especially when the orders are plenty.

Making Login Api with custom django user model with my defined username and emp_password fields

Custom User model authentication not work for me
i need to override default password field with my define emp_password field because in database i have already created users with their passwords field name as emp_password.
I try to map my username and password with employee table emp_password field.I try this last 2 days so still stuck in this issue.
Please help me thank you in advance.
Let share with you code
models.py
Hello everyone, Custom User model authentication not work for me
i need to override default password field with my define emp_password field because in database i have already created users with their passwords field name as emp_password.
I try to map my username and password with employee table emp_password field and then if everything work then make login api for employee login
Let share with you code
models.py
from django.db import models
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.hashers import make_password
class CustomUserManager(BaseUserManager):
"""
Custom user model manager where email is the unique identifiers
for authentication instead of usernames.
"""
def create_user(self, emp_email, password, **extra_fields):
"""
Create and save a User with the given email and password.
"""
if not emp_email:
raise ValueError('The Email must be set')
email = self.normalize_email(emp_email)
user = self.model(emp_email=email, **extra_fields)
user.set_password(password)
user.save(using=self.db)
return user
def create_superuser(self, emp_email, password, **extra_fields):
"""
Create and save a SuperUser with the given email and password.
"""
user = self.create_user(
emp_email,
password=password,
**extra_fields
)
user.is_superuser = True
user.is_admin = True
user.save(using=self._db)
return self.create_user(emp_email, password, **extra_fields)
class Factory(models.Model):
factory_id = models.BigAutoField(primary_key=True)
factory_name = models.CharField(max_length=100)
address = models.TextField()
email = models.CharField(max_length=100)
account_name = models.CharField(max_length=200, null=True, blank=True)
account_number = models.CharField(max_length=200, null=True, blank=True)
bank = models.CharField(max_length=300, null=True, blank=True)
branch = models.CharField(max_length=300, null=True, blank=True)
branch_contact_no = models.CharField(max_length=50, null=True, blank=True)
swift_code = models.CharField(max_length=100, null=True, blank=True)
iban = models.CharField(max_length=100, null=True, blank=True)
phone = models.CharField(max_length=20, null=True, blank=True)
fax = models.CharField(max_length=20, blank=True, null=True)
po_box = models.CharField(max_length=15, null=True, blank=True)
description = models.TextField()
operational_head = models.CharField(max_length=100)
logo = models.TextField()
website = models.CharField(max_length=100, null=True, blank=True)
company_color = models.CharField(max_length=100, null=True, blank=True)
tin = models.CharField(max_length=100, null=True, blank=True) # Taxpayer Identification Number
pan = models.CharField(max_length=100, null=True, blank=True) # Permanent Account Number
reg_date = models.DateField()
status = models.PositiveBigIntegerField(default="0")
reg_no = models.CharField(max_length=150, null=True, blank=True)
license_issue_date = models.DateField(null=True, blank=True)
license_expiry_date = models.DateField(null=True, blank=True)
trash = models.IntegerField(default=0)
reference_num_count = models.IntegerField(default=0)
reference_num_year = models.IntegerField(null=True, blank=True)
short_name = models.CharField(max_length=255, null=True, blank=True)
class Meta:
managed = True
db_table = 'factory'
class Employee(AbstractBaseUser, PermissionsMixin):
emp_password = models.CharField(max_length=100)
username = models.CharField(max_length=50, unique=True)
emp_id = models.BigAutoField(primary_key=True)
factory = models.ForeignKey(Factory, on_delete=models.CASCADE, default=1)
user_type = models.CharField(max_length=50)
emp_first_name = models.CharField(max_length=100)
emp_last_name = models.CharField(max_length=100)
emp_gender = models.CharField(max_length=15, null=True, blank=True)
emp_image = models.CharField(max_length=100)
emp_address = models.CharField(max_length=50, null=True, blank=True)
emp_per_address = models.TextField()
emp_city = models.CharField(max_length=15, null=True, blank=True)
emp_postal_code = models.CharField(max_length=10, null=True, blank=True)
emp_email = models.CharField(max_length=100, blank=True, null=True)
emp_thumb_no = models.CharField(max_length=20, blank=True, null=True)
emp_designation = models.CharField(max_length=100, blank=True, null=True)
act_designation = models.CharField(max_length=100, blank=True, null=True)
emp_mobile = models.CharField(max_length=30, blank=True, null=True)
emp_guardian_mobile = models.CharField(max_length=30, blank=True, null=True)
emp_joining_date = models.DateField(null=True, blank=True)
emp_salary = models.FloatField(null=True, blank=True)
basic_salary = models.FloatField(default='0')
emp_bank_ac_no = models.CharField(max_length=100 ,null=True, blank=True)
currency = models.CharField(max_length=50 ,null=True, blank=True)
emp_dob = models.DateField(null=True, blank=True)
emp_marital_status = models.CharField(max_length=20 ,null=True, blank=True)
emp_blood_group = models.CharField(max_length=20 ,null=True, blank=True)
emp_status = models.PositiveSmallIntegerField(default=0) #'0 -> Active,1 -> Deactive'
training_status = models.PositiveSmallIntegerField(default=0) # '0 -> traing persuing,a->trainign complete'
trash = models.PositiveSmallIntegerField(default=0)
share_factory = models.CharField(max_length=50, default="1")
emp_father_name = models.CharField(max_length=60, null=True, blank=True)
nationality = models.CharField(max_length=50, default="0")
religion = models.CharField(max_length=60, null=True, blank=True)
country = models.CharField(max_length=60, null=True, blank=True)
drivinglicense = models.CharField(max_length=10, null=True, blank=True)
experience_years = models.CharField(max_length=25, null=True, blank=True)
dateofapplication = models.CharField(max_length=150, null=True, blank=True)
salary_expectation = models.CharField(max_length=20, null=True, blank=True)
previouscompanyname = models.CharField(max_length=200, null=True, blank=True)
remarks = models.TextField()
acco_allow = models.CharField(max_length=50, null=True, blank=True)
trans_allow = models.CharField(max_length=50, null=True, blank=True)
over_time = models.CharField(max_length=50, null=True, blank=True)
bank_name = models.CharField(max_length=200, null=True, blank=True)
bank_branch = models.CharField(max_length=200, null=True, blank=True)
acc_type = models.CharField(max_length=50, null=True, blank=True)
joining_date = models.CharField(max_length=60, null=True, blank=True)
leave_information = models.CharField(max_length=255, null=True, blank=True)
laborcontractperiod = models.CharField(max_length=50, null=True, blank=True)
visaperiod = models.CharField(max_length=50, null=True, blank=True)
passport_period = models.CharField(max_length=50, null=True, blank=True)
passport_number = models.CharField(max_length=200, null=True, blank=True)
company_email = models.CharField(max_length=100, null=True, blank=True)
company_mobile = models.CharField(max_length=15, null=True, blank=True)
company_activity = models.CharField(max_length=200, null=True, blank=True)
terminated_by = models.CharField(max_length=50, null=True, blank=True)
last_modified = models.DateTimeField(auto_now_add=True, null=True, blank=True)
modified_by = models.CharField(max_length=80, null=True, blank=True)
block = models.PositiveSmallIntegerField(default=0) # 'Deactive employee . He can not login after block',
shared_status = models.PositiveSmallIntegerField(default=0)
login_active = models.PositiveSmallIntegerField(default=1) #'0 -inactive , 1 active'
created = models.DateTimeField(auto_now_add=True)
created_by = models.CharField(max_length=200, null=True, blank=True)
annual_leave_count = models.IntegerField(default=0)
sick_leave_count = models.IntegerField(default=0)
annual_leave_count_date = models.DateField(null=True, blank=True)
sick_leave_count_date = models.DateField(null=True, blank=True)
last_working_date = models.DateField(null=True, blank=True)
group_name = models.CharField(max_length=255, null=True, blank=True) #'Sales Team, ECS, Management'
objects = CustomUserManager()
EMAIL_FIELD = 'emp_email'
USERNAME_FIELD = "username"
REQUIRED_FIELDS = ["emp_email"]
class Meta:
managed = True
db_table = 'employee'
def clean(self):
super().clean()
self.emp_email = self.__class__.objects.normalize_email(self.emp_email)
def get_full_name(self):
"""
Return the first_name plus the last_name, with a space in between.
"""
full_name = "%s %s" % (self.emp_first_name, self.emp_last_name)
return full_name.strip()
def get_short_name(self):
"""Return the short name for the user."""
return self.emp_first_name
settings.py
AUTH_USER_MODEL = "login_app.Employee"
Remember tables already created
urls.py
from django.contrib import admin
from django.urls import path
from .views import ExampleView, UserLoginApiView
urlpatterns = [
path('api/',ExampleView.as_view()),
path('', UserLoginApiView.as_view()),
]
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.settings import api_settings
from rest_framework.authentication import TokenAuthentication
from rest_framework.authtoken.views import ObtainAuthToken
class ExampleView(APIView):
# authentication_classes = [SessionAuthentication, BasicAuthentication]
# permission_classes = [IsAuthenticated]
authentication_classes = [TokenAuthentication]
def get(self, request, format=None):
content = {
'user': str(request.user), # `django.contrib.auth.User` instance.
'auth': str(request.auth), # None
}
return Response(content)
def post(self, request, format=None):
print("request,", request['username'])
content = {
'user': str(request.user), # `django.contrib.auth.User` instance.
'auth': str(request.auth), # None
}
return Response(content)
class UserLoginApiView(ObtainAuthToken):
""" user login api """
renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES

referral by company's product specific and company specific

I am thinking of creating a referral and reward app where a user will list his/her company with the product they have. A company can use referral program by product specific or just in whole(could not name it properly). For example, I have listed my company called ABC Company and I have a product like smartphone, smart Tvs, Laptops. I would like to market for my company by just saying refer me to 10 people and get something in return(this is non-product specific) or I should be able to market my specific product let's say when user goes to the abc phone XI and there will be refer this phone and get the same phone in return if you refer to more than 50 or if more than 10 then 10% discount etc. This is just an example to demonstrate my project.
For now I created the model for Company, Product(with nested category), referral. But I have no idea on how should i be able to keep the referral based on above example like product specific or based on full company.
Here is what I have done
class Product(models.Model):
"""
product model
"""
name = models.CharField(max_length=100, blank=True)
company = models.ForeignKey(Company, blank=False, null=False, on_delete=models.CASCADE)
category = TreeForeignKey('Category', null=True, blank=True, db_index=True, on_delete=models.CASCADE)
image = models.FileField(upload_to='/company/', max_length=100, blank=True, null=True)
description = models.TextField(blank=True, null=True)
stocks = models.IntegerField(default=0, blank=True)
class Company(models.Model):
"""
company model
"""
name = models.CharField(max_length=150, blank=False, null=False)
domain = models.URLField(blank=False, null=False)
email = models.EmailField()
description = models.TextField(blank=True)
pan_number = models.CharField(max_length=100, blank=False, null=False)
industry = models.CharField(max_length=150, blank=False, null=False)
class Join(models.Model):
"""
Join Model
"""
email = models.EmailField()
friend = models.ForeignKey("self", related_name='referral', null=True, blank=True, on_delete=models.CASCADE)
ref_id = models.CharField(max_length=120, default='ABC', unique=True)
count_added = models.ForeignKey("self", null=True, related_name='count', blank=True, on_delete=models.CASCADE)
ip_address = models.CharField(max_length=120, default='ABC')
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __str__(self):
return '{}'.format(self.email)

create custom role in django to employees

I have created a role model for Employee so that employee will be assigned to control
the overall app based on his/her role. I mean if the role of employee is given can_create_only, then the employee should be able to create inventory, orders, items etc and if employee is given can_create_edit_and_delete, then the employee would be like one of the admin and etc. For this I have designed the model as below but I want to know what is the best way to handle such and why?
Should I go with middleware or decorator way? Can anyone give me an example, please?
class Role(models.Model):
name = models.CharField(max_length=100, blank=False, null=False)
class Meta:
verbose_name = 'Role'
verbose_name_plural = 'Roles'
class Employee(models.Model):
office = models.ForeignKey(
OfficeSetup, blank=False, null=False, on_delete=models.CASCADE)
name = models.CharField(max_length=150, blank=False, null=False)
designation = models.ForeignKey(Designation, blank=False, null=False)
section = models.ForeignKey(DepartmentSetup, blank=True, null=True)
phone_number = models.CharField(max_length=150, blank=True, null=True)
mobile_number = models.CharField(max_length=150, blank=True, null=True)
email = models.EmailField(max_length=150, blank=False, null=False)
gender = models.CharField(
max_length=4, choices=GENDER, blank=True, null=True)
role = models.ForeignKey(Role, blank=True, null=True)
username = models.CharField(max_length=100, blank=False, null=False)
password = models.CharField(max_length=100, blank=False, null=False)
avatar = models.ImageField(
null=True, blank=True, upload_to=upload_employee_image_path)
class Meta:
verbose_name = 'Employee'
verbose_name_plural = 'Employees'
def __str__(self):
return self.name
When creating an employee by admin, the username, password and email, the admin provides will create a new user instance along with the employee
Django comes with Groups and permissions which provides all most everything you are looking for.
This may help you - How do I use Django groups and permissions?
Django documentation - https://docs.djangoproject.com/en/1.11/topics/auth/

query for daily count in django

I have a log model as
models.py
class Log(models.Model):
module = models.CharField(null=False, blank=False,default=None, max_length=20)
mobile = models.CharField(null=False, blank=False,max_length=15)
incoming_text = models.TextField(null=False, blank=False,)
outgoing_text = models.TextField(null=False, blank=False,)
shortcode = models.CharField(null=False, blank=False, max_length=6)
network = models.CharField(null=True, blank=False, max_length=15)
user = models.CharField(null=True, blank=False, max_length=15)
created_on = models.DateTimeField(auto_now_add=True, null=False, blank=False)
campaign = models.CharField(null=False, blank=False, max_length=30)
now I have to generate the query in django such that the total daily count on the basis of created_on field is reqquired. how can I acheive it in django?
Log.objects.filter(pub_date=datetime.date.today()).count() . This should work

Categories