I am trying to write a python statement to calculate a user's dob in a mysql db. The dob is a auto-populated field (based off his profile) in a form that a user fills out.
We write python code directly into the fields in our mysql db that perform calculations on runtime. An example:
date.today().strftime("%m-%d-%Y") for today's date.
But I have never used it in reference to another field on the same form, so I am unsure how to do this. I have tried:
(date.today() - dob) / timedelta(days=365.2425).strftime("%m-%d-%Y")
where dob is the field on the form where the user's date of birth is auto-populated.
What am I missing? I receive a 'syntax error', probably because it doesn't know what the dob variable is, but I don't know how to point to that field's value to make it perform the calc. Any help would be appreciated!
So, just in case you find yourself using Python and MySQL, here is the correct answer - this must be placed in a field designated to pull from the db, and depending on the code, it would be:
round(datediff(now(), s.dob))/365.25
or
concat(round(datediff(now(), s.dob))/365.25)
where s.dob is a field in another table. Not sure if this will help anybody, but thought I would post in nevertheless. Thanks!
Related
I'm working on a website that has to do with user entering data to fields of a table. There is (input type=date) in top of the page. I want the user to enter values daily. but I want to save that data in the database according to that day and if the user change the date, I want to clear some fields for that day for a new fresh entry.
I also don't know if there should be a datefield in model or not?? If so, would I have to populate the database with lots of dates? and if it reach the last date, I have to populate it again and so on??
How I go about doing this?
I tried looking for a solution but couldn't find one that seems good. I found I could use crontab in django or scheduler but I don't think this is the optimum solution.
In my form I have a field that I want to default as Today when launching the form:
class ExpenseForm(forms.ModelForm):
date = forms.DateField(initial=datetime.now(), widget=forms.DateInput(attrs={'id':'datepicker'}))
Now if I go to the form I see it working correctly, it's got today's date populated, (for example "2018-12-03") but then when I come in tomorrow, it STILL has yesterday's date populated. In fact it will not update until I somehow restart the server.
Any idea?
Thank you.
I am new to Django. I would have better grasp of this in Rails but am not familiar enough with all the libraries and converstions in Python / Django.
I have a model:
class Status(models.Model):
created = models.DatetimeField(auto_now_add=True)
This results in the format:
"created": "2017-01-06T22:21:51.531723Z"
I was hoping to see if before saving to the DB that it stores as a UNIX value?
This looked promising https://stackoverflow.com/a/34843855/3007294 but can't get it working. Every time I try to create a Status object, I get this error:
Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z].
My intentions are to not have to enter this every time a Status object is created.
Thanks -
My intentions are to not have to enter this every time a Status object is created.
This is already taken care of with the auto_now_add=True option. When you create a Status object, the created field will be populated with the current datetime.
I was hoping to see if before saving to the DB that it stores as a UNIX value?
You can convert the datetime value from Status.created to a Unix timestamp anytime required. Storing it in the default database datetime format (which is what DatetimeField does) is generally preferred to storing it as a timestamp, which is just an integer.
However, the library used in the example you provided, django-unixdatetimefield, states that "UnixDateTimeField is based on the implementation of the standard Django DateTimeField, making it 100% compatible with all features and options it supports." So, you should be able to provide the auto_now_add=True option to that field.
I am building a survey website using Django 1.7.7 and Python 3.4.4, where a user enters say his "name" and "id". I have a sql table called "list" that stores all the users names and id's. I would like my Django website to check if when a user enters his/her name and id, if the id already exists in the table for the past 30 days. Basically if the user's id exists in the past 30 days, he/she will not be prompted to take the survey, else they would have to take the survey.
I know I have to build a view function that checks this condition but I am unable to figure out what the query/logic should be. Any help on the view function would help me out in my development immensely! Thank you.
You can add "timestamp" field to your List model. You can even make Django automatically set it to now() using auto_now_add parameter
timestamp = models.DateTimeField(auto_now_add=True)
Than you can check if there are records with the same name and id within last month:
from django.utils.timezone import now
import datetime
is_duplicate = List.objects.filter(id=id, name=name, timestamp__gte = now() - datetime.timedelta(days=30))
Note usages of __gte construtions - it means "greater than", and can be used with numbers and timestamps. This filter will only return records created within past 30 days. Hope this helps!
I have a HTML form with field which takes input as month
<input type='month' name="last_appraisal" id='txtLastAppraisal' value='2013-12' />
In my Django model this field is defined as
last_appraisal = models.DateField(blank=True, null=True)
When I try to save this value (received from request.POST) in database then I get format error.
last_appraisal = request.POST.get('last_appraisal','')
if last_appraisal != '':
mymodel.last_appraisal = last_appraisal
mymodel.save()
ERROR: raise exceptions.ValidationError(msg)
ValidationError: [u"'2013-01' value has an invalid date format. It must be in YYYY-MM-DD format."]
I know I can achieve this by adding a default day(maybe 01) to this input month and then save into the database. And while fetching back this value I can re-format it like "YYYY-MM" and send it back to template.
But I want to know if there's any better way to achieve this. I am using Django 1.5.1 and Python 2.7.
EDITED:
After reading all the responses it is clear that Django doesn't have built-in support for this format. Now I have few choices
My way to add day into date field.
As suggested by #Odif to take database field as 'CharField'
As suggested by #Ghopper21 to create a Custom Django field
My preference will be the choice1 because using this
I don't have to write some extra complex code compare to choice3.
I get the flexibility to use this field in table searches like 'find all candidates who got their appraisal in Jun 2013' which I loose if I go for chioce2.
Don't know whether my choice is good or bad but considering the size of project and time to complete it I think this will be the best choice. Please comment if you think this is absolutely rubbish or if you are in favor of this approach.
There are two issues here: Django doesn't have a built-in way to deal with month/year-only dates, and nor does Python.
If you are ok with a convenient way to translate the month/year-only dates into full dates with the day set to 1, but just don't want to have to do this manually in your view code every time, you can encapsulate that logic in a custom Django widget, which is a component for translating between the Django field representation (in this case a DateField) and the HTML input field.
If you need to have the underlying Python representation of the date to be month/year-only in a first class way, I'd suggest looking into the excellent Python library dateutil's relativedelta class -- which allows you to specify things like relativedelta(year=2013, month=12). If you want to use that, you'd then have to create a custom Django model field that translates between relativedelta instances and database storage via serialization. You'd then still need a custom widget for the HTML side of things.
Use models.CharField. DateField and DateTimeField expect date and datetime object respectively. Since '2013-01' cannot be coerced into either, then use CharField. Or use integerfield and just post month.