I have a field in my model
published_on = models.DateTimeField()
on a Django template page and I want to show only the date instead of date along with time. Any idea how to truncate the time form date in the django model form?
Thanks in advance.
Use the date filter in your template, for instance:
{{ form.published_on|date:"D d M Y" }}
Or just:
{{ form.published_on|date }}
You can customize the output the way you want, or use the locale default. See this link for details.
You could try to use SplitDateTimeWidget to represent the field in two widgets (https://docs.djangoproject.com/en/dev/ref/forms/widgets/#splitdatetimewidget). Then, for example, the time field could be hidden with CSS. This method is particularly useful if you need to preserve the actual time value, and just allow user to change the date.
Related
I have a problem of solving this for the whole day and can't get it right. Please someone help me...
book_obj =
Book.objects.filter(status_sold=True).order_by('-date_sold')
result will be something like this:
id = 2
title = 'bla bla bla bla...'
author = 3 ---> id from the User model (not a foreign key)
status_sold = True
date_sold = '2021-05-10'
I want to view that data in the template, but the author I want to display the name instead of number 3 as an id of the author. How to solve this ?
author_name = User.objects.get(id= ???????? )
so I can use {{ author_name.get_full_name }} later in the template
Thx in advanced....
Use this in a template. The author user object is already attached to the book object so you don’t need to fetch it from the database again.
{{ book_obj.author.get_full_name }}
Another option is to set the__str__ method on the user object to
def __str__(self):
return self.get_full_name
Then in the template you can just do
{{ book_obj.author }}
If you show a bit more of your models, it may be easier to provide a more concrete answer, but I think we've got enough to give some help.
In your template, where you have author like :
{{author}}
you can simply add on the property you want with dot notation:
{{author.full_name}}
or what ever you put for the field containing the full name.
No need to separately pass a user object in your context. This way works well in loops as well.
Link to documentation: https://docs.djangoproject.com/en/3.2/topics/templates/#variables
EDIT: apologies - missed the no foreign key bit.
you may be looking at custom template tags.
from django.template.defaulttags import register
#register.filter
def get_author_name(key):
author = Author.objects.get(pk=key)
return author.full_name
then use it in template like:
{{ author|get_author_name }}
You could probably jazz it up a bit and add an attribute as an arg. See: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters
That's it i want to change the way its displayed cause it says "noon" or "midnight" and i want i to display the exact hour
I've got this code on the field
date = models.DateTimeField(auto_now_add=True, default=datetime.date.today())
You have 3 options.
Override DATETIME_FORMAT, read here: datetime format
Use a form for your model and in the date attribute have some like this(
in input format, put whatrever you want):
date = forms.DateTimeField(input_format="%b %d %Y %I:%M%p")
Or just change the way you render your datetime field in the template:
{{ your_model.date_field|date:'Y-m-d H:i' }}
I am using formset for my project. I have several form in my formset. Now I want to customize the appearance of form. I want to do this by using the order value of each form. One example of the input for an "ORDER" of form is shown below:
<input type="text" name="phones-0-ORDER" value="1" id="id_phones-0-ORDER">
I want to get the value(value="1" in this case) of this input.
I have generated the formset from my models directly using the inlineformset_factory in my view.
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#using-an-inline-formset-in-a-view
At the creation of my formset, I have used the following code:
PhoneNumberFormSet = inlineformset_factory(Patron, PhoneNumber, can_order=True)
In this way, every form in the formset will have an order. Let's say we have 3 forms in the formset, the first form will hold the order 1, the second order 2, the third order 3.
I want to use the "order" of the form in my template to control a loop.
Anyone knows how to get the order value in template?
For your information, the type of ORDER is IntegerField. So my question is equal to "how to get the initial(pre filled-in) data of an IntegerField in template.
Thanks for your answers!
I believe you are asking how to set initial data within a formset. If that is the case, you will find the following information valuable within the django docs:
https://docs.djangoproject.com/en/dev/topics/forms/formsets/#using-initial-data-with-a-formset
If you are actually asking about how to get to the values from the client side, you would want to do so with jquery selectors.
http://api.jquery.com/category/selectors/
{% if form.can_order %}
{{ form.ORDER }}
{% endif %}
Given:
from django.db import models
class MyModel(models.Model):
...
owners = models.CharField(max_length=255, blank=False)
where owners is a pipe-separated list of email addresses.
In the page, there are multiple <input> fields with the same name, so the server gets the values in an array.
The HTML code for the form was done by-hand and doesn't use built-in templates (such as form.as_p).
Can Django's ModelForms handle something like this?
What is the proper location to handle the data transformation, both when retrieving the model (do I have to make a custom models.Manager?) and when saving it (which save() method do I override? the Model's or the ModelForm's)?
--UPDATE FOR CLARIFICATION--
In the database:
+-----+---------------------------+-----+
| ... | owners | ... |
+-----+---------------------------+-----+
| ... | "a#a.com|b#b.com|c#c.com" | ... |
+-----+---------------------------+-----+
The form:
<form ... >
...
<input type="text" name="owners" />
<input type="text" name="owners" />
<input type="text" name="owners" />
...
</form>
You can use forms.MultiValueField and forms.MultiWidget. MultiValueField knows that your model's one field contains multiple discrete values and the MultiWidget widget knows how each discrete value should be presented. They'll handle creating unique names for your fields so that they can reconstruct the form from POST values and you won't have to override any form methods that provide implementation, i.e. you won't have to override save().
As you can see, the official docs are a bit thin on the topic. I suggest you take a peek at the code to figure out how everything is wired and what gets called when, since your requirements are always going to need a unique solution, i.e: how many emails will the field contain? Exactly two, so I can specify two CharField widgets by hand, or is it going to be between 0-2, so I have to dynamically construct everything depending on the value passed? If you need a good example as a starting reference, check out this SO question which contains a clean and easy to follow implementation.
Ideally, you'll want to have a PipedEmailAddressesField that extends CharField as your model's field, one that knows that it's storing piped email addresses. It should be able to construct it's own appropriate MultiValueField form field which should in turn construct it's own appropriate MultiWidget field.
Here is an example of saving a modelform in a view:
http://themorgue.org/blog/2008/05/14/django-and-modelform/
You can get the extra fields manually using request.POST['fieldname']
Hope this helped.
Greetings,
I am trying to implement a TimeField model which only consists of HH:MM (ie 16:46) format, I know it is possible to format a regular Python time object but I am lost about how to manage this with Django.
Cheers
Django widget can be used to achieve this easily.
from django import forms
class timeSlotForm(forms.Form):
from_time = forms.TimeField(widget=forms.TimeInput(format='%H:%M'))
DateTime fields will always store also seconds; however, you can easily tell the template to just show the hours and minute, with the time filter:
{{ value|time:"H:M" }}
where "value" is the variable containing the datetime field.
Of course, you can also resort to other tricks, like cutting out the seconds from the field while saving; it would require just a small change to the code in the view handling the form, to do something like this:
if form.is_valid():
instance = form.save(commit=False)
instance.nosecs = instance.nosecs.strptime(instance.nosecs.strftime("%H:%M"), "%H:%M")
instance.save()
(note: this is an ugly and untested code, just to give the idea!)
Finally, you should note that the admin will still display the seconds in the field.
It should not be a big concern, though, because admin should be only used by a kind of users that can be instructed not to use that part of the field.
In case you want to patch also the admin, you can still assign your own widget to the form, and thus having the admin using it. Of course, this would mean a significant additional effort.
So I think the proposed and accepted solution is not optimal because with:
datetime.widget = forms.SplitDateTimeWidget(time_format=('%H:%M'))
For a SplitDateTimeField in my case but for you only change it to TimeWidget.
Hope it helps other people too.
TimeField model
in Template
Is displayed
{{ value|time:"H:i" }}
Is not displayed
{{ value|time:"H:M" }}
Django 1.4.1
For a ModelForm, you can easily add a widget like this, to avoid the seconds being shown (just show hh:mm):
class MyCreateForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ('time_in', 'time_out', )
widgets = {
'time_in': forms.TimeInput(format='%H:%M'),
'time_out': forms.TimeInput(format='%H:%M'),
}
You can at least modify the output in the __str__ method on the model by using datetime.time.isoformat(timespec='minutes'), like this:
def __str__(self):
return self.value.isoformat(timespec='minutes')
Now the value is showing as HH:MM in admin pages.
On Django 1.9 the following format should work:
{{ yourData.value|time:"H:i" }}
Django has a whole set of template tags and filters.
Django 1.9 documentation on this is:
https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#time