How to show from database to Django Data Field? - django

I select date using DateField and insert date value using this.
form = DateField(widget=SelectDateWidget(years=BIRTH_YEAR_CHOICES))
and then, I want to show selected value using DateField(form) in HTML from database
(when create profileForm())
Birth: selectbox(------), selectbox(------), selectbox(------)
: solved
(if edit profile page using profileForm())
Birth: selectbox(1987) selectbox(10) selectbox(25)
-> I want it
How to insert value into DataField, and show selectDateWidget?

Your problem is not too clear.
You should post more information from you forms.py and your views.py. Are you using forms.Form or forms.ModelForm?
Either way I think your question is about using initial data in your form.
Note that this field in particular accepts a python datetime object (see: http://docs.python.org/2/library/datetime.html).
https://docs.djangoproject.com/en/dev/ref/forms/api/#dynamic-initial-values
Use is like this:
f = ContactForm(initial={'my_date_field': datetime.datetime.now()})
If you are using ModelForm is is like this:
f = ContactForm(instance=Contact.objects.get(pk=1))
This will initialise all the values from the models (and thus database).

Related

Django - modify a field value just for filtering purpose

I want to modify some_date_field value just for filtering purpose.
Like using models.Lookup or models.Transform but I dont want to make a raw sql expression.
For instance, using a raw ms sql expression I could write:
WHERE CONVERT(date, FORMAT(some_date_field, '2021MMdd')) >= #some_var
But I how I can do that with Django?
class SomeModel(models.Model):
some_date_field = models.DateField()
def replace_year(value):
return value.replace(year=2021)
SomeModel.objects.filter(
# replace_year(some_date_field)__gte=some_var
)
Is it possible?
You can use SomeModel.objects.filter({whatever you want to filter}).update(some_date_field={date_value})
if you have any issues see:
https://docs.djangoproject.com/en/3.2/ref/models/querysets/#django.db.models.query.QuerySet.update
If you are trying to bulk update all of the objects returned by a queryset and you are using Django 2.2 or greater you can use 'bulk_update'.
See here: Django Bulk Update
If you are dynamically updating values based off of another field check out F expressions they can be used with an 'update' on querysets.
See here: Update dynamically with F expressions
Something to note though, this won't use ModelClass.save method (so if you have some logic inside it won't be triggered).
Take a look at these answers here as well
you can use filter() and update() methods in django
Assuming we need to filter some known year which is the old_date variable and the new value contains in the new_date variable
# defing mehod to filter and update new date
def update_date(old_date, new_date):
SomeModel.objects.filter(some_date_field=old_date).update(some_date_field=new_date)
return None
you can find some examples using this link.
Hope this will be helpful for you.

How to properly use dates in object filters

I'm using Django ORM to access database models, it works well when I use objects.all(), it returns all the objects in the database. But when I want to filter on a date I add a filter using the new date type it doesnt return anything, I get a blank QuerySet. After searching and trying different things for many hours I discovered object.filter(date__gte=date) works.
For example:
This works, I get all the records where date = today:
today = date.today()
Model.objects.filter(date__gte=today)
These do not work, they return empty QuerySets:
Model.objects.filter(date__contains=today)
Model.objects.filter(date__startswith=today)
Model.objects.filter(date__date=date.today())
My question is what am I doing wrong that one type of query works but not the other, when they should all return the same data?
You can do it like this(Reference) for DateTimeField:
Model.objects.filter(date__date=datetime.today())
If its a DateField, then simply do:
Model.objects.filter(date=datetime.today())

Extract nested value from a Django jsonfield

Is there a way to query an object, 'extract' a nested piece of data from a JSONField field and then make it available as a custom, temporary field on each instance of the Queryset?
In my use case, I'm storing overflow metadata from Twitter's API in a data field for later use. I'd like to be able to access the nested field followers_count within TwitterPost.data.
I've read the docs about how to filter based on nested values but not how to extract it as a temporary field when generating a queryset.
Similarly, I've read the annotate docs for ways to create a custom temporary field but the examples all use aggregation functions on simple fields, so not JSONFields.
Thanks in advance for any suggestions.
Example model:
from django.contrib.postgres.fields import JSONField
class TwitterPost(models.Model):
id = models.IntegerField()
data = JSONField()
Example JSON value for the data field:
{
'followers_count': 7172,
"default_profile_image": false,
"profile_text_color": "000000"
}
Pseudocode for what I'd like to be able to do:
TwitterPost.objects.annotate(followers_count=instance.data.followers_count)
This is probably a late answer, but there is a way to do it
from django.contrib.postgres.fields.jsonb import KeyTransform
TwitterPost.objects.annotate(followers_count=KeyTransform('followers_count', 'data'))
OR KeyTextTransform could be used instead of KeyTransform (for converting to string)
If you want to access the data inside a JSONField, you've to use __. In your example it will be something like this
TwitterPost.objects.annotate(followers_count=instance.data__followers_count)
Take a look to the documentation here

Trying to filter the contents of a ChoiceField

(My english no is good, sorry) I have a problem creating a form of search by location: I have the form.py currently as follows:
from models import City, Zone
class SearchForm1(forms.Form):
cityf = forms.ModelChoiceField(queryset=City.objects.all(), empty_label="none")
zonef = forms.ModelChoiceField(queryset=Zone.objects.all(), empty_label="none")
But this is displayed with all cities and areas exist in the db, and I'm trying to make is that in the 1 st field is show all cities and in the 2nd field to display only those areas corresponding to the selected city.
I tried to do so:
class SearchForm1(forms.Form):
cityf = forms.ModelChoiceField(queryset=City.objects.all(), empty_label="none")
zonef = forms.ModelChoiceField(queryset=City.objects.get(
name_city="cityf").zone_set.all(), empty_label="none")
^ But I recive this ##ERROR: ^
Exception Type: DoesNotExist
Exception Value:
City matching query does not exist.
Exception Location:
I've also been looking at this: http://www.stereoplex.com/blog/filtering-dropdown-lists-in-the-django-admin But in the end it does not need to leave it someone can help me out?
You can't do this. Since at the time the form gets rendered, the city (the first field) is not selected yet.
You could either do it in a two-step wizard-style form. Where the first form only has the city, then the second form only the zone. In the second form you filter the zones using the city that was selected in the first form.
Alternatively you could to it using javascript where you filter the second field depending on the first field.
You probably want to use the feature Grouped Selects in django smart selects. Check out this answer to a duplicate question:
https://stackoverflow.com/a/8390892/538471

Django Autoselect Foreign Key Value

I have a model that contains a foreign key value, then in the form generated from this model, I want to auto select the record's key according to the record I'm adding the form's contents to...I've tried the below code, but it tells me QuerySet doesn't contain vehicle
stock = Issues.objects.filter(vehicle=id)
form = IssuesForm(initial={'id_vehicle': stock.vehicle})
I'm a bit new to django btw so any ideas are highly appreciated
filter always gives a QuerySet, which is a set of values. If you just want a single object, you should use get.
However I don't really understand why you need to do the lookup at all. You have the id value already, since you are using it to look up stock. So why don't you just pass id as the value for id_vehicle?