<form action="." method="POST"><table>{%for f in form %}<tr><td>{{ f.name }}</td><td>{{ f }}</td></tr>{% endfor %}</table><input type="submit" name="submit" value="Add Product"></form>
How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view?
I have looked through the Django forms documentation, and it briefly mentions django.contrib.admin.widgets, but I don’t know how to use it?
Here is my template that I want it applied on.
<form action="." method="POST">
<table>
{% for f in form %}
<tr> <td> {{ f.name }}</td> <td>{{ f }}</td> </tr>
{% endfor %}
</table>
<input type="submit" name="submit" value="Add Product">
</form>
Also, I think it should be noted that I haven’t really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py:
{% load adminmedia %}/*At the top of the template.*//*In the head section of the template.*/<script type="text/javascript">
window.__admin_media_prefix__ ="{% filter escapejs %}{% admin_media_prefix %}{% endfilter %}";</script>
The growing complexity of this answer over time, and the many hacks required, probably ought to caution you against doing this at all. It’s relying on undocumented internal implementation details of the admin, is likely to break again in future versions of Django, and is no easier to implement than just finding another JS calendar widget and using that.
That said, here’s what you have to do if you’re determined to make this work:
Define your own ModelForm subclass for your model (best to put it in forms.py in your app), and tell it to use the AdminDateWidget / AdminTimeWidget / AdminSplitDateTime (replace ‘mydate’ etc with the proper field names from your model):
from django import forms
from my_app.models import Product
from django.contrib.admin import widgets
class ProductForm(forms.ModelForm):
class Meta:
model = Product
def __init__(self, *args, **kwargs):
super(ProductForm, self).__init__(*args, **kwargs)
self.fields['mydate'].widget = widgets.AdminDateWidget()
self.fields['mytime'].widget = widgets.AdminTimeWidget()
self.fields['mydatetime'].widget = widgets.AdminSplitDateTime()
Change your URLconf to pass ‘form_class’: ProductForm instead of ‘model’: Product to the generic create_object view (that’ll mean “from my_app.forms import ProductForm” instead of “from my_app.models import Product”, of course).
In the head of your template, include {{ form.media }} to output the links to the Javascript files.
And the hacky part: the admin date/time widgets presume that the i18n JS stuff has been loaded, and also require core.js, but don’t provide either one automatically. So in your template above {{ form.media }} you’ll need:
This implies that Django’s admin media (ADMIN_MEDIA_PREFIX) is at /media/admin/ – you can change that for your setup. Ideally you’d use a context processor to pass this values to your template instead of hardcoding it, but that’s beyond the scope of this question.
This also requires that the URL /my_admin/jsi18n/ be manually wired up to the django.views.i18n.javascript_catalog view (or null_javascript_catalog if you aren’t using I18N). You have to do this yourself instead of going through the admin application so it’s accessible regardless of whether you’re logged into the admin (thanks Jeremy for pointing this out). Sample code for your URLconf:
Lastly, if you are using Django 1.2 or later, you need some additional code in your template to help the widgets find their media:
{% load adminmedia %} /* At the top of the template. */
/* In the head section of the template. */
<script type="text/javascript">
window.__admin_media_prefix__ = "{% filter escapejs %}{% admin_media_prefix %}{% endfilter %}";
</script>
I find myself referencing this post a lot, and found that the documentation defines a slightly less hacky way to override default widgets.
(No need to override the ModelForm’s __init__ method)
However, you still need to wire your JS and CSS appropriately as Carl mentions.
forms.py
from django import forms
from my_app.models import Product
from django.contrib.admin import widgets
class ProductForm(forms.ModelForm):
mydate = forms.DateField(widget=widgets.AdminDateWidget)
mytime = forms.TimeField(widget=widgets.AdminTimeWidget)
mydatetime = forms.SplitDateTimeField(widget=widgets.AdminSplitDateTime)
class Meta:
model = Product
Reference Field Types to find the default form fields.
{% load adminmedia %}/*At the top of the template.*//*In the head section of the template.*/<script type="text/javascript">
window.__admin_media_prefix__ ="{% filter escapejs %}{% admin_media_prefix %}{% endfilter %}";</script>
Starting in Django 1.2 RC1, if you’re using the Django admin date picker widge trick, the following has to be added to your template, or you’ll see the calendar icon url being referenced through “/missing-admin-media-prefix/”.
{% load adminmedia %} /* At the top of the template. */
/* In the head section of the template. */
<script type="text/javascript">
window.__admin_media_prefix__ = "{% filter escapejs %}{% admin_media_prefix %}{% endfilter %}";
</script>
Complementing the answer by Carl Meyer, I would like to comment that you need to put that header in some valid block (inside the header) within your template.
Note: Using admin widgets for date-time fields is not a good idea as admin style-sheets can conflict with your site style-sheets in case you are using bootstrap or any other CSS frameworks. If you are building your site on bootstrap use my bootstrap-datepicker widget django-bootstrap-datepicker-plus.
Step 1: Add javascript-catalog URL to your project’s (not app’s) urls.py file.
What about just assigning a class to your widget and then binding that class to the JQuery datepicker?
Django forms.py:
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['my_date_field'].widget.attrs['class'] = 'datepicker'
And some JavaScript for the template:
$(".datepicker").datepicker();
回答 10
使用required = False更新了SplitDateTime的解决方案和解决方法:
表格
from django import forms
classSplitDateTimeJSField(forms.SplitDateTimeField):def __init__(self,*args,**kwargs):
super(SplitDateTimeJSField, self).__init__(*args,**kwargs)
self.widget.widgets[0].attrs ={'class':'vDateField'}
self.widget.widgets[1].attrs ={'class':'vTimeField'}classAnyFormOrModelForm(forms.Form):
date = forms.DateField(widget=forms.TextInput(attrs={'class':'vDateField'}))
time = forms.TimeField(widget=forms.TextInput(attrs={'class':'vTimeField'}))
timestamp =SplitDateTimeJSField(required=False,)
I use this, it’s great, but I have 2 problems with the template:
I see the calendar icons twice for every filed in template.
And for TimeField I have ‘Enter a valid date.‘
models.py
from django.db import models
name=models.CharField(max_length=100)
create_date=models.DateField(blank=True)
start_time=models.TimeField(blank=False)
end_time=models.TimeField(blank=False)
forms.py
from django import forms
from .models import Guide
from django.contrib.admin import widgets
class GuideForm(forms.ModelForm):
start_time = forms.DateField(widget=widgets.AdminTimeWidget)
end_time = forms.DateField(widget=widgets.AdminTimeWidget)
create_date = forms.DateField(widget=widgets.AdminDateWidget)
class Meta:
model=Guide
fields=['name','categorie','thumb']
回答 12
在Django 10中,myproject / urls.py:urlpatterns的开头
from django.views.i18n importJavaScriptCatalog
urlpatterns =[
url(r'^jsi18n/$',JavaScriptCatalog.as_view(), name='javascript-catalog'),...]
June 3, 2020 (All answers didn’t worked, you can try this solution I used. Just for TimeField)
Use simple Charfield for time fields (start and end in this example) in forms.
forms.py
we can use Form or ModelForm here.
class TimeSlotForm(forms.ModelForm):
start = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'HH:MM'}))
end = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'HH:MM'}))
class Meta:
model = TimeSlots
fields = ('start', 'end', 'provider')
Convert string input into time object in views.
import datetime
def slots():
if request.method == 'POST':
form = create_form(request.POST)
if form.is_valid():
slot = form.save(commit=False)
start = form.cleaned_data['start']
end = form.cleaned_data['end']
start = datetime.datetime.strptime(start, '%H:%M').time()
end = datetime.datetime.strptime(end, '%H:%M').time()
slot.start = start
slot.end = end
slot.save()