I'm new to Django. whenever I render the form I get "Exception has occurred: VariableDoesNotExist
Failed lookup for key [required_css_class] in " . I don't understand this error if anybody explain or tell me what I'm doing wrong will be much appreciated
thank you in advance
this is my view
def considerations(request):
if request.method == "POST":
form = B2bConsideration(request.POST)
v = form.is_valid()
if form.is_valid():
instance = form.save(commit=True)
#adding date to instance from request not in table but a good idea
#instance.date = request.date
instance.save()
return HttpResponseRedirect(reverse('b2b:TypeOfTitle'))
else:
return HttpResponse(form.errors)
else:
form = B2bConsideration()
return render(request, 'b2b/B2B_notes.html',{'form':form} )
this is my modelform
class B2bConsideration(ModelForm):
CHOICES = [('yes_title_under_name', 'yes'),('No_title_under_name','no'),]
under_name_title = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect())
class Meta:
model = Consideration
fields = ['under_name_title','salvage_title','is_title_paidoff']
this is my model
under_Name_choices = [('yes_title_under_name', 'yes'),('No_title_under_name','no'),]
salvage_title_choices =[('yes_salvage_title','yes'),('no_salvage_title','no'),]
is_title_paidoff_choices = [('yes_title_paidoff', 'yes'),('no_title_paidoff','no'),]
class Consideration (models.Model):
under_name_title = models.CharField(max_length=21, choices=under_Name_choices)
salvage_title = models.CharField(max_length=18, choices=salvage_title_choices)
is_title_paidoff = models.CharField(max_length=21, choices=is_title_paidoff_choices)
here is where the error points to. this is what it said "Exception has occurred: VariableDoesNotExist
Failed lookup for key [required_css_class] in "
<label class="control-label {{ classes.label }} {% if field.field.required %}{{ form.required_css_class }}{% endif %}">{{ field.label }}</label>
this is my HTML
{% load static %}
{% load materializecss %}
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Titlemax B2B</title>
{% block css %}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
{% endblock css %}
{% block javascript %}
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
{% endblock javascript %}
<script src="{% static 'B2B_index.js' %}"></script>
<link rel="stylesheet" href="{% static 'B2B_index.css' %}">
</head>
{{ form.under_name_title.0}}
{{ form.under_name_title.1}}
{{ form|materializecss:'m6' }}
I think the problem is that you are overriding the variable "form" by passing it to your template with the line:
return render(request, 'b2b/B2B_notes.html',{'form':form} )
Try renaming your variable to something other than 'form', such as:
return render(request, 'b2b/B2B_notes.html',{'my-form':form} )
Make sure to also rename the variable in your html in the last 3 lines where you call {{ form }}
If I render a static image in the .html template it works. But if I provide the static markup string as dictionary value to the template (the context), it will not work. It seems to be something to do with string formatting and not allowing me to use {% %} the way I need to. I have tried:
1. .format()
2. escaping the percent characters
3. raw strings
4. concatenation
5. autoescape
6. | safe
and a number of other things
Basically, I am constructing a multi-line string in view.py with '''{% %}''', and then rendering a template with this string as the context. Python 2.
UPDATE
Simple non-working example:
view.py
def index(request):
image_insert = ''
images = ['image1.jpg', 'image2.jpg', 'image3.jpg']
for image in images:
image_insert += '<img src="{}">'.format(image)
context = {'insert': image_insert}
template = loader.get_template('index.html')
return HttpResponse(template.render(context, request))
index.html
{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>Basic HTML File</title>
</head>
<body>
First Image
<img src={% static "image.jpg" %}>
Second Image <!-- does not work -->
{{ image_insert | safe }}
</body>
</html>
Page Source:
<!DOCTYPE html>
<html>
<head>
<title>Basic HTML File</title>
</head>
<body>
<img src=/static/mqdefault.jpg>
Second Image
<img src="image1.jpg"><img src="image2.jpg"><img src="image3.jpg">
</body>
</html>
Obviously, there is a difference. This is Django 1.11 btw if it makes a difference.
You can also achieve this by passing img source from the view as follow:
views.py
from django.contrib.staticfiles.templatetags.staticfiles import static
def index(request):
context = {'image_src': static("image.jpg")}
template = loader.get_template('index.html')
return HttpResponse(template.render(context, request))
index.html
<!DOCTYPE html>
<html>
<head>
<title>Basic HTML File</title>
</head>
<body>
<img src="{{ image_src }}">
</body>
</html>
UPDATE: Multiple Images
You can generate markup with multiple images and pass it in the context as seen in the views.py:
views.py
from django.contrib.staticfiles.templatetags.staticfiles import static
def index(request):
images = [static('image1.jpg'), static('image2.jpg'), static('image3.jpg')]
images_html = "".join([
"<img src={image}>".format(image=image)
for image in images
])
context = {'images_html': images_html)}
template = loader.get_template('index.html')
return HttpResponse(template.render(context, request))
Now, your updated index.html will be:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Basic HTML File</title>
</head>
<body>
{{ images_html|safe }}
</body>
</html>
Hope it helps.
working code:
def index(request):
context = {'image_insert': "image.jpg"}
template = loader.get_template('index.html')
return HttpResponse(template.render(context, request))
index.html
{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>Basic HTML File</title>
</head>
<body>
First Image
<img src="{% static "image.jpg" %}">
Second Image <!-- does not work -->
<img src="{% static image_insert %}">
</body>
</html>
I'm trying to get a file that's in my media directory to appear on an HTML template. I'm using the "Tango with Django" book as a tutorial.
Here is my settings.py:
MEDIA_DIR = os.path.join(BASE_DIR, 'media')
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'
Here is views.py:
def about(request):
return render(request, 'rango/about.html', )
And my about.html template:
<!DOCTYPE html>
{%load staticfiles%}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>About</title>
</head>
<body>
<h1>This is the about page</h1>
<img src="{{MEDIA_URL}} {{cat.jpg}}"
alt="cats are funny"/>
<div>
Index
</div>
</body>
</html>
I know I must be missing something very obvious, but can't figure it out for the life of me!
The {{MEDIA_URL}} tag is deprecated. Use the {% get_media_prefix %} tag, instead.
<img src="{% get_media_prefix %}cat.jpg" alt="cats are funny"/>
From the documentation:
Similar to the get_static_prefix, get_media_prefix populates a template variable with the media prefix MEDIA_URL.
When rendered, that src attribute will be equivalent to /media/cat.jpg. You may want to consider using STATIC_ROOT in your settings.py, instead, along with the {% static %} tag:
<img src="{% static 'cat.jpg' %}" alt="cats are funny"/>
I think the problems should be errors in format.
Try the following two revisions:
1. in your render(), change "return render(request, 'rango/about.html', )" to "return render(request, 'rango/about.html') by deleting the last comma;
2. in your template file about.html, change .
In my django project there are some mysterious (at least for me as a beinner) outputs I don't understand while working in my development environment.
I wanted to have a base template which includes a stylesheet in a static media folder...this works so far...but just for the address http://localhost/ all the other urls have a template which inherits from the base template.
Now the stylesheet of http://localhost/ looks nice...if i go to http://localhost/hello/ the included stylesheet has a whole html DOM structure with body, doctype etc. why is that? He somehow parses a html site instead of taking the css file...
Here my code: Any ideas?
urls.py:
from django.views.static import *
from django.conf import settings
admin.autodiscover()
urlpatterns = patterns('',
('^$',home_view),
('^hello/$', hello),
(r'^admin/', include(admin.site.urls)),
('^useragent/$',ua_display_good1),
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
)
views.py
from django.http import HttpResponse
from django.shortcuts import render_to_response
def hello(request):
pagetitle = "Hello World"
return render_to_response('hello.tpl', {'pagetitle': pagetitle})
def home_view(request):
pagetitle = "Something"
return render_to_response('home.tpl', {'pagetitle': pagetitle})
def ua_display_good1(request):
try:
ua = request.META['REMOTE_ADDR']
except KeyError:
ua = 'unknown'
return render_to_response('base.tpl',{'ageone': ua})
base template:
<!DOCTYPE html>
<html lang="de">
<meta name="description=" content="{{metadescription}}">
<head>
<link rel="stylesheet" type="text/css" href="media/style.css">
<title>{% block title %}{{pagetitle}}{% endblock %}</title>
</head>
<body>
<h1>{% block h1 %}{{ageone}}{% endblock %}</h1>
{% block content %}{% endblock %}
{% block footer %}{% include "footer.tpl" %}
{% endblock %}
</body>
</html>
hello template:
{% extends "base.tpl" %}
{% block h1 %}Home{% endblock %}
{% block content %}Welcome{% endblock %}
Probably because you have a relative reference to the CSS file.
Try changing:
<link rel="stylesheet" type="text/css" href="media/style.css">
to
<link rel="stylesheet" type="text/css" href="/media/style.css">
so it always look in the root for media/style.css
Now you have set the link to css as relative "media/style.css". In home it resolves to "/media/style.css" but in hello it resolves to "/hello/media/style.css" (which gives the hello page).
Just use absolute css link like this: "/media/style.css".
The proper way to include the style sheets would be
<link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}style.css">
if this still wont work ....my css file name is Stylesheet.css and i linked it as css/Stylesheet.css ..it wasnt working... then i changed it to css/Stylesheet.CSS ..and it worked
Change href="media/style.css" to href="media/style.CSS" and it will work.
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:
(r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}),
And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy...
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:
<script type="text/javascript" src="/my_admin/jsi18n/"></script>
<script type="text/javascript" src="/media/admin/js/core.js"></script>
You may also wish to use the following admin CSS (thanks Alex for mentioning this):
<link rel="stylesheet" type="text/css" href="/media/admin/css/forms.css"/>
<link rel="stylesheet" type="text/css" href="/media/admin/css/base.css"/>
<link rel="stylesheet" type="text/css" href="/media/admin/css/global.css"/>
<link rel="stylesheet" type="text/css" href="/media/admin/css/widgets.css"/>
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:
(r'^my_admin/jsi18n', 'django.views.i18n.javascript_catalog'),
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>
Thanks lupefiasco for this addition.
As the solution is hackish, I think using your own date/time widget with some JavaScript is more feasible.
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.
My head code for 1.4 version(some new and some removed)
{% block extrahead %}
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/forms.css"/>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/base.css"/>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/global.css"/>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/widgets.css"/>
<script type="text/javascript" src="/admin/jsi18n/"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/core.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/admin/RelatedObjectLookups.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/jquery.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/jquery.init.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/actions.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/calendar.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/admin/DateTimeShortcuts.js"></script>
{% endblock %}
Yep, I ended up overriding the /admin/jsi18n/ url.
Here's what I added in my urls.py. Make sure it's above the /admin/ url
(r'^admin/jsi18n', i18n_javascript),
And here is the i18n_javascript function I created.
from django.contrib import admin
def i18n_javascript(request):
return admin.site.i18n_javascript(request)
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.
{% block extra_head %}
<link rel="stylesheet" type="text/css" href="/media/admin/css/forms.css"/>
<link rel="stylesheet" type="text/css" href="/media/admin/css/base.css"/>
<link rel="stylesheet" type="text/css" href="/media/admin/css/global.css"/>
<link rel="stylesheet" type="text/css" href="/media/admin/css/widgets.css"/>
<script type="text/javascript" src="/admin/jsi18n/"></script>
<script type="text/javascript" src="/media/admin/js/core.js"></script>
<script type="text/javascript" src="/media/admin/js/admin/RelatedObjectLookups.js"></script>
{{ form.media }}
{% endblock %}
For Django >= 2.0
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.
from django.views.i18n import JavaScriptCatalog
urlpatterns = [
path('jsi18n', JavaScriptCatalog.as_view(), name='javascript-catalog'),
]
Step 2: Add required JavaScript/CSS resources to your template.
<script type="text/javascript" src="{% url 'javascript-catalog' %}"></script>
<script type="text/javascript" src="{% static '/admin/js/core.js' %}"></script>
<link rel="stylesheet" type="text/css" href="{% static '/admin/css/widgets.css' %}">
<style>.calendar>table>caption{caption-side:unset}</style><!--caption fix for bootstrap4-->
{{ form.media }} {# Form required JS and CSS #}
Step 3: Use admin widgets for date-time input fields in your forms.py.
from django.contrib.admin import widgets
from .models import Product
class ProductCreateForm(forms.ModelForm):
class Meta:
model = Product
fields = ['name', 'publish_date', 'publish_time', 'publish_datetime']
widgets = {
'publish_date': widgets.AdminDateWidget,
'publish_time': widgets.AdminTimeWidget,
'publish_datetime': widgets.AdminSplitDateTime,
}
The below will also work as a last resort if the above failed
class PaymentsForm(forms.ModelForm):
class Meta:
model = Payments
def __init__(self, *args, **kwargs):
super(PaymentsForm, self).__init__(*args, **kwargs)
self.fields['date'].widget = SelectDateWidget()
Same as
class PaymentsForm(forms.ModelForm):
date = forms.DateField(widget=SelectDateWidget())
class Meta:
model = Payments
put this in your forms.py from django.forms.extras.widgets import SelectDateWidget
Here's another 2020 solution, inspired by #Sandeep's. Using the MinimalSplitDateTimeMultiWidget found in this gist, in our Form as below, we can use modern browser date and time selectors (via eg 'type': 'date'). We don't need any JS.
class EditAssessmentBaseForm(forms.ModelForm):
class Meta:
model = Assessment
fields = '__all__'
begin = DateTimeField(widget=MinimalSplitDateTimeMultiWidget())
Another simple solution for Django 3 (3.2) in 2021 ;) cause andyw's solution doesn't work in Firefox...
{% load static %}
{% block extrahead %}
{{ block.super }}
<script type="text/javascript" src="{% static 'admin/js/cancel.js' %}"></script>
<link rel="stylesheet" type="text/css" href="{% static 'admin/css/forms.css' %}">
<script src="{% url 'admin:jsi18n' %}"></script>
<script src="{% static 'admin/js/jquery.init.js' %}"></script>
<script src="{% static 'admin/js/core.js' %}"></script>
{{ form.media }}
{% endblock %}
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Сохранить">
</form>
and you'll able to use your form.
example:
from django.contrib.admin import widgets
date_time = forms.SplitDateTimeField(widget=widgets.AdminSplitDateTime)
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();
Updated solution and workaround for SplitDateTime with required=False:
forms.py
from django import forms
class SplitDateTimeJSField(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'}
class AnyFormOrModelForm(forms.Form):
date = forms.DateField(widget=forms.TextInput(attrs={'class':'vDateField'}))
time = forms.TimeField(widget=forms.TextInput(attrs={'class':'vTimeField'}))
timestamp = SplitDateTimeJSField(required=False,)
form.html
<script type="text/javascript" src="/admin/jsi18n/"></script>
<script type="text/javascript" src="/admin_media/js/core.js"></script>
<script type="text/javascript" src="/admin_media/js/calendar.js"></script>
<script type="text/javascript" src="/admin_media/js/admin/DateTimeShortcuts.js"></script>
urls.py
(r'^admin/jsi18n/', 'django.views.i18n.javascript_catalog'),
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']
In Django 10.
myproject/urls.py:
at the beginning of urlpatterns
from django.views.i18n import JavaScriptCatalog
urlpatterns = [
url(r'^jsi18n/$', JavaScriptCatalog.as_view(), name='javascript-catalog'),
.
.
.]
In my template.html:
{% load staticfiles %}
<script src="{% static "js/jquery-2.2.3.min.js" %}"></script>
<script src="{% static "js/bootstrap.min.js" %}"></script>
{# Loading internazionalization for js #}
{% load i18n admin_modify %}
<script type="text/javascript" src="{% url 'javascript-catalog' %}"></script>
<script type="text/javascript" src="{% static "/admin/js/jquery.init.js" %}"></script>
<link rel="stylesheet" type="text/css" href="{% static "/admin/css/base.css" %}">
<link rel="stylesheet" type="text/css" href="{% static "/admin/css/forms.css" %}">
<link rel="stylesheet" type="text/css" href="{% static "/admin/css/login.css" %}">
<link rel="stylesheet" type="text/css" href="{% static "/admin/css/widgets.css" %}">
<script type="text/javascript" src="{% static "/admin/js/core.js" %}"></script>
<script type="text/javascript" src="{% static "/admin/js/SelectFilter2.js" %}"></script>
<script type="text/javascript" src="{% static "/admin/js/admin/RelatedObjectLookups.js" %}"></script>
<script type="text/javascript" src="{% static "/admin/js/actions.js" %}"></script>
<script type="text/javascript" src="{% static "/admin/js/calendar.js" %}"></script>
<script type="text/javascript" src="{% static "/admin/js/admin/DateTimeShortcuts.js" %}"></script>
My Django Setup : 1.11
Bootstrap: 3.3.7
Since none of the answers are completely clear, I am sharing my template code which presents no errors at all.
Top Half of template:
{% extends 'base.html' %}
{% load static %}
{% load i18n %}
{% block head %}
<title>Add Interview</title>
{% endblock %}
{% block content %}
<script type="text/javascript" src="{% url 'javascript-catalog' %}"></script>
<script type="text/javascript" src="{% static 'admin/js/core.js' %}"></script>
<link rel="stylesheet" type="text/css" href="{% static 'admin/css/forms.css' %}"/>
<link rel="stylesheet" type="text/css" href="{% static 'admin/css/widgets.css' %}"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
<script type="text/javascript" src="{% static 'js/jquery.js' %}"></script>
Bottom Half:
<script type="text/javascript" src="/admin/jsi18n/"></script>
<script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.min.js' %}"></script>
<script type="text/javascript" src="{% static 'admin/js/jquery.init.js' %}"></script>
<script type="text/javascript" src="{% static 'admin/js/actions.min.js' %}"></script>
{% endblock %}
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()