Django model is inheriting all super model Fields, except for IntegerField - django

I'm having a weird issue, I have a models' hierarchy, an abstract User class:
class User(AbstractBaseUser):
user_name = models.CharField(max_length=32, unique=True)
email = models.EmailField(max_length=255, unique=True, null=True)
phone = PhoneNumberField()
access_token = models.CharField(max_length=255, unique=True, null=True)
notifications_token = models.CharField(max_length=255, unique=True, null=True)
photo = models.ImageField(null=True)
person_in_contact = models.CharField(max_length=32, null=True)
active = models.BooleanField(default=False)
confirmedEmail = models.BooleanField(default=False)
confirmedPhone = models.BooleanField(default=False)
completedProfile = models.BooleanField(default=False)
visible = models.BooleanField(default=True)
#property
def is_active(self):
return self.active
# def __str__(self):
# return "Client : " + self.user_name + " Email:" + self.email
def get_email(self):
return self.email
USERNAME_FIELD = 'user_name'
REQUIRED_FIELDS = ['user_name', 'phone', 'password']
class Meta:
abstract = True
then a person class and a company (no issue with this one) class that inherit from this one:
class Person(User):
GENDER = (('F', 'FEMALE'), ('M', 'MALE'))
name = models.CharField(max_length=50, null=True)
surname = models.CharField(max_length=50, null=True)
adress = models.CharField(max_length=255, null=True)
birth_date = models.DateField(null=True)
gender = models.CharField(max_length=1, choices=GENDER, null=True)
age = models.IntegerField(null=True)
def age(self):
today = date.today()
return today.year - self.birth_date.year
# def __str__(self):
# return super().__str__() + " Name : " + self.name
class Meta:
abstract = True
as you can see, the only field that's IntegerField() is the age field.
now i have a Traveller and a Driver classes that inherit from the person class,
the issue is the age field, doesn't show in the database, unless i override it in one of the classes, that's what i did, i override it in traveller so it appeared in the database, but didn't override it in the driver, so it didn't show.
Traveller:
class Traveller(Person):
photo = models.ImageField(null=True, upload_to='travellers/profile_pictures')
age = models.IntegerField(null=True)
class Meta:
verbose_name_plural = 'Travellers'
Driver:
class Driver(Person):
rating = models.DecimalField(default=0, decimal_places=1, max_digits=3)
driving_license = models.CharField(max_length=50, null=True)
insurance_number = models.CharField(max_length=50, null=True)
company = models.ForeignKey(TransportCompany, on_delete=models.DO_NOTHING, null=True)
photo = models.ImageField(null=True, upload_to='drivers/profile_pictures')
i need to know how i can fix this, or what's the issue, any help is appreciated.

The reason this happens is because your age field has the same name as the age function. As a result, the age = ... field is ignored by Python in favor of the age function, since that is the last time you defined the age variable.
For the same reason the age field pops up in sublasses: you defined an age variable over there, and that takes precedence over the "inherited" age method.
You should rename one of the two. For example with:
class Person(User):
GENDER = (('F', 'FEMALE'), ('M', 'MALE'))
name = models.CharField(max_length=50, null=True)
surname = models.CharField(max_length=50, null=True)
adress = models.CharField(max_length=255, null=True)
birth_date = models.DateField(null=True)
gender = models.CharField(max_length=1, choices=GENDER, null=True)
_age = models.IntegerField(null=True)
def age(self):
today = date.today()
bod = self.birth_date
before_dob = (today.month, today.day) < (bod.month, bod.day)
return today.year - self.birth_date.year - before_dob
class Meta:
abstract = True
Note that the calculation of the age was not completely accurate: if we are before the birthday of that year, you need to subtract one from the age.

Related

I want to assign a user to my card from the User table, but its not working for me

The error is:
django.db.utils.ProgrammingError: column
user_awaycardholder.assigned_user_id does not exist LINE 1:
...der"."id", "user_awaycardholder"."display_id_id", "user_away...
I am not able to create AwayCardHolder can you please tell me what is the above error ??? and How to fix that ?
class UserData(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
title = models.CharField(max_length=40, default="")
phone = models.CharField(max_length=15)
facebook_id = models.CharField(max_length=400)
youtube_id = models.CharField(max_length=400)
linkedin_id = models.CharField(max_length=400)
instagram_id = models.CharField(max_length=400)
twitter_id = models.CharField(max_length=400)
logo = models.ImageField(upload_to='logo')
profile_image = models.ImageField(upload_to='media/profile')
location = models.CharField(max_length=400)
website = models.CharField(max_length=100)
messanger = models.CharField(max_length=200)
parent_id = models.CharField(max_length=20, blank=True)
is_child = models.BooleanField(default=False)
phone_office = models.CharField(max_length=15, blank=True)
hits = models.IntegerField(max_length=10, default=0)
class Meta:
verbose_name_plural = "User Data"
def __str__(self):
name = self.user.first_name + ' ' + str(self.user.id)
return str(name)
class AwayCard(models.Model):
Away_id = models.UUIDField(default=uuid.uuid4, editable=True)
my_admin = models.ForeignKey(User, on_delete=models.CASCADE)
display_id = models.CharField(default='', max_length=30)
is_assigned = models.BooleanField(default=False)
def __str__(self):
name = str(self.display_id)
return str(name)
class AwayCardHolder(models.Model):
display_id = models.OneToOneField(AwayCard, on_delete=models.CASCADE)
assigned_user = models.ForeignKey(User, related_name="user_awaycardholder", on_delete=models.CASCADE)
def __str__(self):
name = self.display_id
return str(name)

django - How can I prefill formset forms data using database query result?

I am creating a student attendance form where need to get details of student name, student class and Id from student model based on teacher selecting student class in one form. I have tried using initial by using for loop on query data to prefill the form in formset, however it populates data for one record only. Below is the code for forms.py, models and views.py. Can someone help on this
forms.py
class student(models.Model):
studentid = models.AutoField(primary_key=True)
Gender = models.CharField(max_length=6, choices=gender, null=True)
Name = models.CharField(max_length=100, null=True)
DOB = models.DateField(null=True)
Image = models.ImageField(null=True, upload_to='images')
Status = models.CharField(max_length=10, choices=statchoice, null=True)
Father_name = models.CharField(max_length=100, null=True)
Mother_name = models.CharField(max_length=100, null=True)
Address = models.CharField(max_length=200, null=True)
Contact_no = models.IntegerField(null=True)
Email = models.EmailField(null=True)
Admission_class = models.CharField(max_length=40, null=True, choices=grade)
Admission_date = models.DateField(null=True)
Current_class = models.CharField(max_length=40, null=True, choices=grade)
Leaving_date = models.DateField(null=True, blank=True)
objects = models.Manager()
def __str__(self):
return str(self.studentid)
class student_attendance(models.Model):
Student_ID = models.CharField(max_length=100, null=True)
Student_Name = models.CharField(max_length=100, null=True)
Student_class = models.CharField(max_length=100, null=True, choices=grade)
Attendance_date = models.DateField(null=True, auto_now_add=True, blank=True)
Attendance_status = models.CharField(choices=attendance, null=True, max_length=10)
objects = models.Manager()
Views.py
def student_attend(request):
if request.method == 'POST':
data = request.POST.get('studentGrade')
formset_data = student.objects.filter(Current_class=data)
AttendanceFormSet = formset_factory(std_attendance, extra=(len(formset_data))-1)
for element in formset_data:
formset = AttendanceFormSet(initial=[
{'Student_ID': element.studentid, 'Student_Name':element.Name, 'Student_class':element.Current_class, 'Attendance_status':"Present"}
])
param = {'formset':formset}
return render(request, 'home/student_attendance.html', param)
return render(request, 'home/student_attendance.html')
form.py:
class student_register(ModelForm):
class Meta:
model = student
fields = '__all__'
class std_attendance(ModelForm):
class Meta:
model = student_attendance
fields = '__all__'
Each iteration in your loop you override the formset, that is why only a single form is filled, you need to fill the param with all the forms inside the loop this way:
initial = []
for element in formset_data:
initial.append({'Student_ID': element.studentid, 'Student_Name':element.Name, 'Student_class':element.Current_class, 'Attendance_status':"Present"}
formset = AttendanceFormSet(initial=initial)

How do I make sure entered integer is greater than current value before updating model field?

I am using a form that saves to one model to update the most current mileage which is stored in another model. I want to make sure the mileage entered is > or = the current mileage. I havent been able to figure out the right validation or where to write the validation.
I have tried an if statement in the form_valid() of the CreateView and a save() method in the model.
Models.py
class Vehicle(models.Model):
name = models.CharField(blank=True, max_length=100)
make = models.CharField(blank=True, max_length=100)
model = models.CharField(blank=True, max_length=100)
year = models.IntegerField(blank=True, null=True)
vin = models.CharField(blank=True, max_length=17)
gvw = models.IntegerField(blank=True, null=True)
license_plate = models.CharField(blank=True, max_length=100)
purchase_date = models.DateField()
current_mileage = models.IntegerField(blank=True, null=True)
class Meta:
ordering = ['name']
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('vehicles:vehicle_detail', kwargs={'pk':self.pk})
#property
def get_current_mileage(self):
return self.current_mileage
class FuelEntry(models.Model):
vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE)
date = models.DateTimeField(auto_now_add=True)
fuel_choices = (
('EMPTY', 'Empty'),
('1/8', '1/8'),
('1/4', '1/4'),
('1/2', '1/2'),
('3/4', '3/4'),
('FULL', 'Full'),
)
current = models.CharField(max_length=5, choices=fuel_choices)
after = models.CharField(max_length=5, choices=fuel_choices, blank=True)
gallons = models.DecimalField(decimal_places=2, max_digits=5, blank=True, default='0')
cost = models.DecimalField(decimal_places=2, max_digits=5, blank=True, default='0')
mileage = models.IntegerField(blank=False)
user = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
ordering = ['-date', 'vehicle']
def __str__(self):
return self.vehicle.name
def get_absolute_url(self):
return reverse('fuellog:entry_detail', kwargs={'pk':self.pk})
Views.py
class CreateEntry(CreateView):
model = FuelEntry
fields = ('vehicle', 'current', 'after', 'gallons', 'cost', 'mileage')
def form_valid(self,form):
self.object = form.save(commit=False)
self.object.user = self.request.user
vehicle_id = self.object.vehicle.pk
mileage = self.object.mileage
self.object.save()
current_mileage = Vehicle.objects.filter(id=vehicle_id).get('current_mileage')
if current_mileage > mileage:
raise ValidationError('Incorrect mileage reading')
Vehicle.objects.filter(id=vehicle_id).update(current_mileage=mileage)
return super().form_valid(form)
ValueError at /fuel/new
too many values to unpack (expected 2)

I need to display summary report in Django admin site. How do I count number of users where gender status is 0 or 1

I am overriding change_list.html and here is what I have in my admin.py file.
class MyHelperGenderAdmin(admin.ModelAdmin):
change_list_template = 'admin/helper_chart_change_list.html'
date_hierarchy = 'created_at'
list_filter = ('gender', 'created_at')
def changelist_view(self, request, extra_context=None):
response = super().changelist_view(request, extra_context=extra_context, )
try:
qs = response.context_data['cl'].queryset
except (AttributeError, KeyError):
return response
metrics = {
'male': Count('gender', gender=1),
'female': Count('gender', gender=0),
'total_helpers': Count('id')
}
response.context_data['helper'] = list(
qs.values('gender').annotate(**metrics).order_by('-male')
)
return response
def has_add_permission(self, request):
return False
admin.site.register(MyHelperChart, MyHelperGenderAdmin)
In my metrics dictionary, i need a way to count where gender is either 0 or 1. Currently, The count method count everything regards of the gender status.
Here is my model:
class Helper(auth.models.User):
MALE = 1
FEMALE = 0
GENDER_CHOICES = (
(MALE, 'Male'),
(FEMALE, 'Female')
)
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
message=
"Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed."
)
phone_number = models.CharField(validators=[phone_regex], max_length=15, blank=True, unique=True, null=True)
gender = models.IntegerField(choices=GENDER_CHOICES, default=MALE, null=True)
birthdate = models.DateField(blank=True, null=True)
facebook_id = models.CharField(max_length=200, blank=True, null=True)
google_id = models.CharField(max_length=200, blank=True, null=True)
lng = models.FloatField(blank=True, null=True)
lat = models.FloatField(blank=True, null=True)
country = models.ForeignKey(Country, blank=True, null=True)
image = models.ImageField(
upload_to=upload_location,
null=True, blank=True,
width_field="width_field",
height_field="height_field")
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
updated_at = models.DateTimeField(auto_now=True)
created_at = models.DateTimeField(auto_now=False, auto_now_add=True)
class Meta:
verbose_name_plural = "Helpers"
def __str__(self):
return self.first_name
class MyHelperChart(Helper):
class Meta:
proxy = True
verbose_name = 'Helper Gender Summmary'
verbose_name_plural = 'Helpers Gender Summaries'
I have created a proxy model which I will be using in my Django admin in order to display summary of data and a chart.
All you need to do is add a case to both the male and female metrics. Here's an example, and then you can do the same for female = 0:
from django.db.models import Case, When, IntegerField
class MyHelperGenderAdmin(admin.ModelAdmin):
...
metrics = {
...
'male': Count(Case(
When(gender = 1, then = 1),
output_field = IntegerField())),
...
}

How To a autoselect Patient Name field when bed assign to patients in Django

How To assign bed to Patient Django?
when I try to assign bed to Patient at that time in bedconfig automatically select Patient Name
then wardconfig file open but Patient name is blant, it must be autoselected Patient name
view this image When click on assign bed
but Patient name is blant, it must be autoselected Patient name
models.py Patient model
class Patient(Auditable):
aadhar_no = models.CharField(max_length=12, blank=True,unique=True)
fullname = models.CharField(max_length=50)
firstname = models.CharField(max_length=30)
middlename = models.CharField(max_length=30)
lastname = models.CharField(max_length=30)
CATEGORY_GENDER= (('Male', 'Male'), ('Female', 'Female'))
gender = models.CharField(max_length=6, choices=CATEGORY_GENDER)
CATEGORY_BG= (('Not known','Not known'),('A+', 'A+'), ('A-', 'A-'),('B+', 'B+'),('B-', 'B-'),('AB+', 'AB+'),('AB-','AB-'),('O+','O+'), ('O-','O-'))
blood_group = models.CharField(max_length=10, choices=CATEGORY_BG)
dob = models.DateField() #Date of birth
photo = models.ImageField(upload_to="Patient/", null=True, blank=True)
education = models.CharField(max_length=15, null=True, blank=True)
CATEGORY_OCC= (('Service', 'Service'), ('Retired', 'Retired'),('Housewife', 'Housewife'), ('Business','Business'),('other','other'))
occupation = models.CharField(max_length=15, choices=CATEGORY_OCC,null=True, blank=True) #service, retired, Housewife, Business, others
current_address = models.TextField()
mobile_number = models.CharField(max_length=12)
mobile_number2 = models.CharField(max_length=12, null=True, blank=True)
phone_number = models.CharField(max_length=12, null=True, blank=True)
email = models.CharField(max_length=30, null=True, blank=True)
country = models.ForeignKey(Country , null=True, blank=True, )
state = models.ForeignKey(State , null=True, blank=True)
district = models.ForeignKey(District , null=True, blank=True)
city = models.ForeignKey(City ,null=True, blank=True)
recreational_drugs= models.BooleanField(default=False) #alocohol, smoking,coffine etc.
current_insurance = models.BooleanField(default=False)
#family = models.ForeignKey(Family) # Family
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self): # __unicode__ on Python 2
# return self.fullname
return str(self.fullname)
class Meta:
verbose_name_plural = "Patient"
models.py WardConfog
class WardConfig(Auditable):
bed = models.ForeignKey(Bed)
ward = models.ForeignKey(Ward)
patient=models.ForeignKey(Patient)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
#def __str__(self): # __unicode__ on Python 2
#return self.name
class Meta:
verbose_name_plural = "Wardconfig"
Views.py PatientCreate(CreateView)
class PatientCreate(CreateView):
model = Patient
form_class = PatientForm
def get_success_url(self):
return reverse_lazy( 'patient')
def form_valid(self,PatientForm):
PatientForm.save()
return HttpResponseRedirect(self.get_success_url())
def form_invalid(self, PatientForm):
return self.render_to_response(self.get_context_data(form=PatientForm))
Views.py
class WardConfig(Auditable):
bed = models.ForeignKey(Bed)
ward = models.ForeignKey(Ward)
patient=models.ForeignKey(Patient)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
#def __str__(self): # __unicode__ on Python 2
#return self.name
class Meta:
verbose_name_plural = "Wardconfig"
please Guys Help me how auto select Patient Name IN Wardconfig when assign bed
Sorry for English
You can give the view you are using to add a WardConfig record a get_initial method. This assumes you are passing a patient_id kwarg in the URL:
def get_initial(self):
patient = get_object_or_404(Patient, pk=self.kwargs.get('patient_id'))
return {
'patient': patient,
}