Birthdays employee Django Model - python

I have a model with employees data, name, photo, date of birth and etc.
I'm trying to create a url that shows the birthdays of the employees where I can filter, if i click at one button, filter the birthdays of the day, another button, birthdays of the week and so on.
I'm don't know where I can work with the date of birth to generate theses "category".
I'm looking for ideas to implement these
Thanks in advance

When you ask,
... where I can work with the date of birth to generate theses 'category'
it sounds like you're asking about a view. Views are Python functions typically placed in a file called views.py.
Let's say you have a model Employee defined in your models.py with a field birthdate (among others):
# models.py
class Employee(models.Model):
employee = models.CharField(
help_text = 'Employee name'
)
birthdate = models.DateField(
help_text = "Employee's birthdate"
)
# other fields...
I'll further assume that you've run makemigrations and migrate on this model so that it has a table in your database (more on migrations). And of course, this won't work in the end unless you put actual data into that database, which is also covered in the docs.
Then in your views.py file, you can import this model and access its fields using code like
# views.py
from yourApp.models import Employee
def bday(request):
employees = Employee.objects.all()
for emp in employees:
bdate = emp.birthdate
# further logic with 'bdate', etc.
The docs have much more on how to access your data in view functions.
Once your view has loaded all of the data you'll want to display on the page, you'll combine that data with a template and use the URLconf settings in your urls.py file to map the bday() view function to whatever URL you want.
The interactivity you mention for applying filters would typically be done using JavaScript, otherwise you'll have to reload the page entirely every time the user changes a filter. That JavaScript would be written in a separate file and included in your template.
The Django docs are imperfect, but they'll certainly help you get a better idea of what you're looking for. In particular, I recommend the tutorial, which you should work through, and the basics of views

Related

Building a django detailview and listview without using <int:pk>

I'm building a django app that displays a database of employees and their salaries. It uses a postgres database. I'm struggling to figure out how to build a DetailView without using a primary key for the url. I think using a slug may be the solution but I'm not sure how to implement that and haven't had much luck searching online.
My Listview for the list of all companies:
class AllCompanies(FormMixin, generic.ListView):
template_name = 'AllCompanies.html'
form_class = SearchForm
model = bigdatabase
queryset = bigdatabase.objects.order_by().values('company').distinct()
context_object_name = 'companies'
Example Database snippet, bigdatabase:
Company EmployeeName Salary
Alpha Jim 100000
Alpha Tim 125000
Beta Bim 90000
My list view displays all unique company names as intended. However, I'm not sure how to proceed and build a detailview to display more info on each unique company. I'd like to show things like number of employees, median salary, etc.
I've done something similar by building a detailview for employees, but that relied upon using their primary key in the url since each employee is unique. Since I have many entries for many companies in my database, how would I build a detailview and accompanying url structure to support that?
Any advice or pointers as to move this along would be greatly appreciated.
You can add a slugfield to your bigdatabase model. Try using the autoslugfield and set it to the company name like:
from django_extensions.db.fields import AutoSlugField
class bigdatabase(models.Model):
company = Models.Charfield()
slug = models.AutoSlugField(populate_from=['company']
......
This makes sure you company name will automatically be translated for use in the url. E.g. when you have spaces in the company name, using str:company will translate in weird characters for the space. Using in your url translates this to a -.
Naming your model field slug makes sure that your detailview get the slug field by default. See docs.
Your views will then look something like:
class CompanyDetailView(DetailView):
model = bigdatabase
template_name = '#path_to_template'
slug_url_kwarg = 'slug' # I believe this is done correctly by default but in case you change the field name.
In your url you can do something like mentioned above:
path('company/<slug>', views.CompanyDetailView.as_view())
Happy coding!
Not sure that I understood correctly, but I thought you can use something like this:
path('company/<str:name>', views.company_detail_view)

Add entries to the choices of a field through the admin site?

I have a model with some default entries in a choices field. I was wondering if it was possible for the admin to add and remove entries to the choices from the admin site. The only other option I see at the moment is to have a separate table for the entries, but the spec specifically says to only use one table and I'm fairly new to Django. The current model code is very basic, and I haven't added any forms to admin.py, only registered my model. Example code:
class Contact(models.Model):
#some other fields here...
...
TYPES = (
('op1','option1'),
('op2','option2'),
('op3','option3')
)
option = models.CharField(
max_length=3,
choices=TYPES,
default='op1'
)
I want the super user to be able to click an add/remove type button on the admin page to open a new box which will allow them to edit the possible types.
Turns out I had to make a new model after all. it's fine, the admin site works as it needs to.

Django. How to create new model, with specific fields (in dropdown) from django admin site?

Im working on page with car ads. But I want to let admin extend the page in the future, let him add from django admin site new category of ads - houses for instance.
I know how to let admin create new ad in existing category,
but how to let admin to create new category with new fields (int, str, Boolean)?
Thanx for anwsers.
Create a Category model:
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=30)
This is the advertisement model
class Adv(models.Model):
your fields here
category = models.ForeignKey()
I have an app for adding Schools see the following images for refrence.
when I click on "Add" against Schools following screen follows
after filling in the necessary details click Save and the School is successfully added!
You should be able to do this with any model you created
Unfortunately I can't share the code the company won't allow but I may be able to help you if you pasted your models.py and the corresponding template. You will also need some javascript to do this. If you are trying to do something like this I may be of help.

get user profile in django

hello i'm new in python and django
I need a view that get current user profile I know I shoud use get_profile from User but I don't know how to use it . i read the django document and It didn't help me.
this is what I found from doc:
from django.contrib.auth.models import User
profile=request.user.get_profile()
Django's documentation says it all, specifically the part Storing additional information about users. First you need to define a model somewhere in your models.py with fields for the additional information of the user:
models.py
from django.contrib.auth.models import User
class UserProfile(models.Model):
# This field is required.
user = models.OneToOneField(User)
# Other fields here
accepted_eula = models.BooleanField()
favorite_animal = models.CharField(max_length=20, default="Dragons.")
Then, you need to indicate that this model (UserProfile) is the user profile by setting AUTH_PROFILE_MODULE inside your settings.py:
settings.py
...
AUTH_PROFILE_MODULE = 'accounts.UserProfile'
...
You need to replace accounts with the name of your app. Finally, you want to create a profile every time a User instance is created by registering a post_save handler, this way every time you create a user Django will create his profile too:
models.py
from django.contrib.auth.models import User
class UserProfile(models.Model):
# This field is required.
user = models.OneToOneField(User)
# Other fields here
accepted_eula = models.BooleanField()
favorite_animal = models.CharField(max_length=20, default="Dragons.")
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
Accessing the Profile
To access the current user's profile in your view, just use the User instance provided by the request, and call get_profile on it:
def your_view(request):
profile = request.user.get_profile()
...
# Your code
Basically django User models will provide access only for the fields ( firstname,lastname,email,password,is_staff,is_active,last_login).
However if we want to add any extra fields to this model, say we need to add a new column named dateofbirth for every user, then we need to add a column named DOB into User model. But this is not possible as we aren't able to edit django User models.
To achieve this either
1.We can have a separate new table with email id & DOB column, such that a column in User model is mapped with a column in the new table. But this will create a new db instance for every db request. Say if u want to find the DOB of a customer,
First we need to fetch the value of mapped id of a customer from the
User table.
WIth the above value, get DOB from the new table.
In the second method,
Instead of using django User model, use your own customize model with all the fields needed. However if any updation related to security or some enhancement made to django User model we can't use it directly. We need to do more code changes at our end( wherever we use our customize models.) This will be a bit pain for a developer to identify the code & make changes.
To overcome the above issues, django introduce django profile which is very simple and more flexible. The advantages are
Updation/enhancement to the User model can be applied without modifying the code much
No need of creating new db instance to fetch the extra values.
Since the field has onetoone mapping deletion of data from one table will delete others also.
More secure, since we use django models ( no sql injection)
How to Use this:
In settings.py create a variable AUTH_PROFILE_MODULE = "appname.profiletable"
In models.py, create a new table with the fields needed and make sure that the id in User model is onetoone mapped with new table.
create a signal which inserts a row into the new table whenever a new entry is added into User model.
The value in the new table can be accessed using User object itself.
Say, we created a new table extrauser which has DOB, emailid. To find the DOB of a customer, use
a=User.objects.get(email='x#x.xom')
a.get_profile().DOB will give the dateofbirth value from extrauser table.
Hope the above details make you clear in understanding django profile. Incase of any help further, let me know. I have used django profile in my project.
Old question but I thought anyone seeing it today may benefit from this:
Django 1.5 adds the ability to - easily - extend the User model. This may be preferable as you now only got one object to deal with rather than two! Seems the more modern way.
https://hurricanelabs.com/blog/django-user-models/
You need to specify which class is your "Profile" by setting AUTH_PROFILE_MODULE = 'accounts.UserProfile' (for example)
https://docs.djangoproject.com/en/1.4/topics/auth/

Formatting inline many-to-many related models presented in django admin

I've got two django models (simplified):
class Product(models.Model):
name = models.TextField()
price = models.IntegerField()
class Invoice(models.Model):
company = models.TextField()
customer = models.TextField()
products = models.ManyToManyField(Product)
I would like to see the relevant products as a nice table (of product fields) in an Invoice page in admin and be able to link to the individual respective Product pages.
My first thought was using the admin's inline - but django used a select box widget per related Product. This isn't linked to the Product pages, and also as I have thousands of products, and each select box independently downloads all the product names, it quickly becomes unreasonably slow.
So I turned to using ModelAdmin.filter_horizontal as suggested here, which used a single instance of a different widget, where you have a list of all Products and another list of related Products and you can add\remove products in the later from the former. This solved the slowness, but it still doesn't show the relevant Product fields, and it ain't linkable.
So, what should I do? tweak views? override ModelForms? I Googled around and couldn't find any example of such code...
Maybe it is not what you expect but I would introduce InvoiceItem model which would link Invoice to Product. So you would have 2x 1:n instead of m:n relation. Then use inline custom form for InvoiceItem and raw_id_fields in that form for Product choice.
In InvoiceItem form then you could add readonly fields that would display values you need to display. You will have to provide data for these fields in Form's init reading them from InvoiceItem instance. Or you could also derive from raw_id_field widget and in render method of this widget append some additional data from the product model?
This is an old question, but I have related to it today.
You can find the answer here - https://blog.ionelmc.ro/2012/01/19/tweaks-for-making-django-admin-faster/
The code:
class MyAdmin(admin.TabularInline):
fields = 'myfield',
def formfield_for_dbfield(self, db_field, **kwargs):
formfield = super(MyAdmin, self).formfield_for_dbfield(db_field, **kwargs)
if db_field.name == 'myfield':
# dirty trick so queryset is evaluated and cached in .choices
formfield.choices = formfield.choices
return formfield
This can cut your waiting times from anything like 5 minutes to around 15 seconds.

Categories

Resources