I am working on a django website which includes a form for contact information and I am currently using bootstrap to make it "look pretty". I want to use bootstrapvalidator http://bootstrapvalidator.com/ to make the form easy to use for my users. I have heavily researched using django and bootstrapvalidator together and have found several different plugins or other ways to validate information entered into a form but they only give errors after the form is submitted, and what I want is live validation that shows the user appropriate messages as they type.
My biggest problem has been figuring out how/where to call the Javascript. I think the correct way to do this is by using a widget in the form, but nothing I have tried has done the job. Currently my page is displaying "emailval(parent_or_guardian_email)" where the email field should be.
Would anyone be able to tell me what I'm doing wrong or how to get my desired result? This is my first time using django or python at all.
relevant parts of my models.py
from django.db import models as db_models
from django.db import models
from django.contrib.auth.models import User
from django import forms
from django.contrib.admin import widgets
from django.forms import extras
import datetime
from django.core.validators import *
from django.forms import ModelForm
from django.contrib import admin
import logging
class EmailWidget(forms.TextInput):
def render(self, name, value, attrs=None):
out = super(EmailWidget,self).render(name, value, attrs=attrs)
return out + '<script type="text/javascript">emailval(parent_or_guardian_email) </script>'
class Media:
js = ('../validator.js')
class PersonForm(forms.Form):
ready_to_play = forms.BooleanField(initial = True )
first_name = forms.CharField(max_length=35)
last_name = forms.CharField(max_length=35)
phone_number = forms.CharField(widget =forms.TextInput(attrs={'type':'text', 'class':'form-control bfh-phone','data-format':"+1 (ddd) ddd-dddd",}), required = False)
grade = forms.IntegerField(initial = 99, required = False)
age = forms.IntegerField(initial = 99, required = False)
gender = forms.ChoiceField(choices=GENDERS, required = False)
sport = forms.ChoiceField(choices=SPORTS, required = False)
#fields for parent_or_guardian and physician not autofilled
parent_or_guardian = forms.CharField(max_length=35, required = False)
parent_or_guardian_phone_number = forms.CharField(widget =forms.TextInput(attrs={'type':'text', 'class':'form-control bfh-phone','data-format':"+1 (ddd) ddd-dddd",}), required = False)
parent_or_guardian_email = forms.EmailField(widget =EmailWidget(),help_text = "Changing this field will create a new user for this email address, if you wish to change this user's contact information"
+" please ask them to do so on their page or contact a site admin ")
physician = forms.CharField(max_length=35, required = False)
physician_phone_number = forms.CharField(widget =forms.TextInput(attrs={'type':'text', 'class':'form-control bfh-phone','data-format':"+1 (ddd) ddd-dddd",}), required = False)
#Pphone = copy.deepcopy(physician.phone)
#Pphone =str(physician_phone)
#physician_phone = re.sub('.','-',str(Pphone))
physician_email = forms.EmailField(max_length=75, required = False)
in my base.html I have the appropriate file imports
<link href ="../../../../static/spotlight/assets/css/bootstrap-responsive.css" rel="stylesheet">
<link href ="../../../../static/spotlight/assets/css/bootstrapValidator.min.css" rel="stylesheet">
<script src="../../../../../static/spotlight/assets/js/jquery-1.11.1.min.js"></script>
<script src="../../../../static/spotlight/assets/js/bootstrap-tab.js"></script>
<script src="../../../../static/spotlight/assets/js/bootstrap.js"></script>
<script src="../../../../static/spotlight/assets/js/bootstrap.min.js"></script>
<script src="../../../../static/spotlight/assets/js/bootstrap-formhelpers.min.js"></script>
<script type="text/javascript" src="../../../../static/spotlight/assets/js/bootstrapValidator.min.js"></script>
the html file for the page with the form
{% extends "spotlight/base.html" %}
{% block content %}
<h3>Update {{ athlete }}</h3>
<br>
<form class="form-horizonal" role="form" action="{% url 'spotlight:athleteedit' athlete.id %}" method="post" id="PersonForm">
{% for field in form %}
<div class="form-group"><p>
{{ field.label_tag }} {{ field }}
{% for error in field.errors %}
<font color="Red">{{ error }}</font>
{% endfor %}
</p></div>
{% endfor %}
{% csrf_token %}
<input class="btn btn-default" type="submit" value="Submit" />
</form>
{% endblock content %}
validators.js
$(document).ready(function emailval() {
$('#PersonForm').bootstrapValidator({
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
parent_or_guardian_email: {
validators: {
emailAddress: {
message: 'The value is not a valid email address'
excluded: [':disabled'],
}
}
}
}
});
});
Ok, I figured it out, it was really quite simple. I included this javascript as the last thing before the closing html tag in my base.html file:
<body>
<script type="text/javascript">
$(document).ready(function() {
$('#PersonForm').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
parent_or_guardian_email: {
validators: {
notEmpty: {
message: 'The email address is required and can\'t be empty'
},
emailAddress: {
message: 'The input is not a valid email address'
}
}
},
}
});
});
</script>
</body>
above which (in base.html) I made sure to include the correct files (order does matter)
<link href ="../../../../static/spotlight/assets/css/bootstrap-responsive.css" rel="stylesheet">
<link href ="../../../../static/spotlight/assets/css/bootstrap.css" rel="stylesheet">
<link href ="../../../../static/spotlight/assets/css/bootstrapValidator.min.css" rel="stylesheet">
and made my html for the page containing the form look like this
{% extends "spotlight/base.html" %}
{% block content %}
<h3> Add Athlete</h3>
<br>
<form class="form-horizonal" role="form" action="{% url 'spotlight:addstu' person_id team_id %}" method="post" >
{% for field in form %}
<div class="fieldWrapper"><p>
{% if field.label = "Parent or guardian email" %}
<div class="col-lg-5" id="PersonForm">
{{ field.label_tag }} {{ field }}
</div>
{% else %}
{{ field.label_tag }} {{ field }}
{% for error in field.errors %}
<font color="Red">{{ error }}</font>
{% endfor %}
{% endif %}
</p></div>
{% endfor %}
{% csrf_token %}
<input class="btn btn-default" type="submit" value="add athlete" />
</form>
{% endblock content %}
and I didn't need to create a widget outside the form, just include it like this
parent_or_guardian_email = forms.EmailField(widget =forms.TextInput(attrs={'type':'text', 'class':'form-control','name':"parent_or_guardian_email",'class':"col-lg-5",}),help_text = "Changing this field will create a new user for this email address, if you wish to change this user's contact information"
+" please ask them to do so on their page or contact a site admin ",max_length=75)
for some reason the feedbackIcons aren't showing, but the validation messages are displaying as the user fills in the field, which is what I really needed. Hope someone else finds this so they don't have to bag their head for as long as I did.
Related
I don't understand how widgets work.
I tried this minimum example :
in my forms.py
class PartialResetForm(forms.Form):
date = forms.DateField(
label="Starting date",
widget=AdminDateWidget()
)
in my admin/intermediary_reset_page.html
{% extends "admin/base_site.html" %}
<!--Loading necessary css and js -->
{{ form.media }}
{% block content %}
<form action="" method="post">{% csrf_token %}
<!-- The code of the form with all input fields will be automatically generated by Django -->
{{ form }}
<!-- Link the action name in hidden params -->
<input type="hidden" name="action" value="custom_action" />
<!-- Submit! Apply! -->
<input type="submit" name="apply" value="Submit" />
</form>
{% endblock %}
in my admin.py as the definition of an action
def custom_action(self, request, queryset):
form = PartialResetForm()
return render(request, "admin/intermediary_reset_page.html", {
"items": queryset, "form": form
})
For now I don't care about the queryset, it will be my next topic. With this simple example, I wanted to have a calendar in order to help pick a date, but only a TextInput appeared. I believe it is due to the fact that AdminDateWidget inheritates from TextInput.
My question is why isn't it appearing as a calendar ? I imported the media and declared my widget, I don't understand what else I'm supposed to do.
you should declare type
AdminDateWidget(attrs={'type': 'date'})
And it should be enough ;)
I am using Django 3.0 and python 3.8.2 to develop an ads website. To add a post, I used Django formtools wizard. It worked and everything goes nicely. I could save the multiform data. However, I could not retrieve the files from the FileSystemStorage so I can save them. Hence, any help to achieve this or suggestion is much appreciated. I want to retrieve uploaded files, save them to the data base and then delete them from the wizard (from the FileSystemStorage). Note: there is no error and everything is working except that the uploaded files are not saved to the data base even though they are available in the FileSystemStorage. Thus, I want to retrieve them to be able to save them to the data base.
Here is the view class:
TEMPLATES = {"CommonForm": "towns/salehslist/ads_main_form.html",
"JobForm": "towns/salehslist/forms/jobPostForm.html",
}
FORMS = [
("CommonForm", CommonForm),
("JobForm", JobForm, JobImagesForm),
]
class PostWizard(SessionWizardView):
# The form wizard itself; will not be called directly by urls.py,
# but rather wrapped in a function that provide the condition_dictionary
_condition_dict = { # a dictionary with key=step, value=callable function that return True to show step and False to not
"CommonForm": True, # callable function that says to always show this step
"JobForm": select_second_step, # conditional callable for verifying whether to show step two
}
file_storage = FileSystemStorage(
location=os.path.join(settings.MEDIA_ROOT, "photos")
)
def get_template_names(self):
return [TEMPLATES[self.steps.current]]
def done(self, form_list, form_dict, **kwargs):
# form_data = [form.cleaned_data for form in form_list]
# print(form_data)
data = {k: v for form in form_list for k, v in form.cleaned_data.items()}
data["posted_by"] = self.request.user
instance = Job.objects.create(**data)
print("YOU ARE HERE")
print(self.request.FILES.getlist("files"))
for file in self.request.FILES.getlist("files"):
print(file)
img_instance = JobImages.objects.create(job=instance, images=file)
img_instance.save()
return HttpResponse("<h1>Post Page </h1>")
Here is the url:
url(r'^post/$', PostWizard.as_view(FORMS, condition_dict = PostWizard._condition_dict)),
Here is the html template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
{% load static %}
{% load crispy_forms_tags %}
{% load i18n %}
<script type="text/javascript" src="{% static 'towns/assets/fontawesome-free-5-12-0-we/js/all.js' %}">
</script>
<link rel="stylesheet" type="text/css" href="{% static 'towns/assets/bootstrap-4.4.1/dist/css/bootstrap.min.css' %}">
<link rel="stylesheet" type="text/css" href="{% static 'towns/assets/fontawesome-free-5-12-0-we/scc/fontawesome.min.css' %}">
<!-- file uploader font -->
<link type="text/css" rel="stylesheet" media="all" href="{% static 'towns/assets/fileuploader-2.2/dist/font/font-fileuploader.css' %}" >
<link rel="stylesheet" type="text/css" href="{% static 'towns/style/forms/jobPostForm.css' %}">
</head>
<body>
<div class="container">
<div class="row h-100">
<div class="col-lg-6 my-auto">
<div class="breadcrumb">
<div class="ads-form-title">
Job Post
</div>
</div>
<form class="" action="" method="POST" enctype="multipart/form-data" novalidate id="jobPost">
{% csrf_token %}
{{ wizard.management_form }}
{{ wizard.form.media }}
<hr>
<div class="form-group">
<div>
{{ wizard.management_form }}
{% if wizard.form.forms %}
{{ wizard.form.management_form }}
{% for form in wizard.form.forms %}
{{ form|crispy }}
{% endfor %}
{% else %}
{{ wizard.form|crispy }}
{% endif %}
</div>
</div>
<hr>
<!-- upload images -->
<!-- file input -->
<input type="file" name="files" class="files">
<center>
<button type="submit" class="btn btn-primary" style="position:relative; width: 33%; height: 100%;"> Submit </button>
</center>
</form>
</div>
</div>
</div>
<script type="text/javascript" src=" {% static 'towns/assets/jquery-3.5.0.min.js' %}">
</script>
<script type="text/javascript" src=" {% static 'towns/assets/bootstrap-4.4.1/dist/js/bootstrap.min.js' %}">
</script>
<script type="text/javascript" src="{% static 'towns/assets/fileuploader-2.2/dist/jquery.fileuploader.min.js' %}" >
</script>
</body>
</html>
When user hit submit button of the form wizard, def post() method is called. def post() will
validate the form and
save data and files into session.
then if the current page is the last page, it will
render_done, which is def done()
The reason why your request.files is empty is because, the current request does not have files or data associated with it. All your data and files are saved to the session when you hit the submit buttons which are preceding the done() method.
Since I do not know how your form is structured, I am not sure how to definetely solve your problem. But something like below should do:
# iterate over all forms in the form_list
for form in form_list:
# check if current form has files
if bool(self.get_form_step_files(form)):
# if yes, do something
uploadedfiles = form.files
print(uploadedfiles)
for key, value in uploadedfiles.items():
jobimage = JobImage(job=?, image=value)
jobimage.save()
Update
wihtout your model, form structure, and template, it is difficult to come out with complete solution. I am posting a minimum working example.
1. in models.py
class MyPost(models.Model):
field1 = models.CharField(max_length=50)
field2 = models.CharField(max_length=50)
class Photo(models.Model):
mypost = models.ForeignKey(MyPost, on_delete=models.CASCADE)
photo = models.FileField(blank=True, null=True)
2. In forms, you will not include photoform, because you are trying to uplaod more than one images.
from .models import MyPost, Image
from django import forms
class step_first_form(forms.ModelForm):
class Meta:
model = MyPost
fields = ['field1']
class step_second_form(forms.ModelForm):
class Meta:
model = MyPost
fields = ['field2']
in template, you can keep your first template same as whatever you have. For the second one, say, you will have MyPost's field2 and 2 image inputs, you will change it to:
<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
<table>
{{ wizard.management_form }}
{% if wizard.form.forms %}
{{ wizard.form.management_form }}
{% for form in wizard.form.forms %}
{{ form }}
{% endfor %}
{% else %}
{{wizard.form.field2}}
<input type="file" name ="imagefile1" >
<input type="file" name ="imagefile2" >
{% endif %}
</table>
.......
.....
.....
</form>
make sure you include enctype="multipart/form-data" otherwise your files will not be uploaded.
make sure you have different names for filefield otherwise only one
will be saved to your model.
4. in views.py
def done(self, form_list, form_dict, **kwargs):
data = [form.cleaned_data for form in form_list]
# you can print out and inspect this data, and you will know
# the below code.
# you will need to modify data[0]['field1'] etc ...
print(data)
mypost = MyPost()
mypost.field1 = data[0]['field1']
mypost.field2=data[1]['field2']
mypost.save()
print('mypost')
print(mypost)
# the below part is for saving image files to model
for form in form_list:
# check which form has files
if bool(self.get_form_step_files(form)):
uploadedfiles= form.files
print(form.files)
for key, value in uploadedfiles.items():
photo = Photo(mypost=mypost,photo=value)
photo.save()
else:
print('not bool')
return render ##### whatever template you want to render
I am trying to display a User's name on top of a box where they enter their Employee # in a form, without having to refresh the page.
For example, they enter their # and then after they click/tab onto the next field, it renders their name on top, which comes from the database, so the user knows they've entered the correct info. This name is stored in a separate model, so I try to retrieve it using the "id/number".
I am not too familiar with AJAX but after reading a few similar questions it seems like an AJAX request would be the most appropriate way to achieve this. I tried to make a function get_employee_name that returns the name of the person based on the way I saw another ajax request worked, but I'm not sure how to implement this so it displays after the # is entered.
My page currently loads, but when I check the network using F12, there is never a call to the function/url that searches for the name to display it on the page. I'm not sure where I might be missing the part that connects these two areas of the code, but I have a feeling it has to do with the html tag where the call is supposed to happen, as I am not too familiar with html and Django.
models.py
class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model):
employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False)
work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False)
station_number = models.ForeignKey(StationNumber, on_delete=models.SET_NULL, null=True, blank=True)
This is the model where the name is stored
alldata/models.py
class Salesman(models.Model):
slsmn_name = models.CharField(max_length=25)
id = models.IntegerField(db_column='number', primary_key=True)
I was reading I can add to the "attrs" in the widget an 'onchange' part, but I am not too familiar with how to approach this and tying it to the ajax request from forms and not the html.
forms.py
class WarehouseForm(AppsModelForm):
class Meta:
model = EmployeeWorkAreaLog
widgets = {
'employee_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('employee_number').remote_field, site, attrs={'id':'employee_number_field'}),
}
fields = ('employee_number', 'work_area', 'station_number')
views.py
def enter_exit_area(request):
form = WarehouseForm(request.POST or None)
if form.is_valid():
# Submission stuff/rules
return render(request, "operations/enter_exit_area.html", {
'form': form,
})
def get_employee_name(request):
employee_number = request.GET.get('employee_number')
try:
employee = Salesman.objects.get(id=employee_number)
except Salesman.DoesNotExist:
return JsonResponse({'error': 'Employee not found'}, status=404)
employee_name = employee.slsmn_name
return JsonResponse({'employee_name': employee_name})
urls.py
urlpatterns = [
url(r'enter-exit-area/$', EnterExitArea.as_view(), name='enter_exit_area'),
path('get-employee-name/', views.get_employee_name, name='get_employee_name'),
]
The ajax request I tried to create is at the end of this html. I modified a similar request I found, but it does not actually display anything on the screen, not sure if I'm missing an area where the request is actually never being called, as I am not too familiar with how these types of requests work.
enter_exit_area.html
{% extends "base.html" %}
{% block main %}
<form id="warehouseForm" action="" method="POST" novalidate >
{% csrf_token %}
<div>
<h1 id="employee_name">{{ employee_name }}</h1>
<div>
{{ form.employee_number.help_text }}
{{ form.employee_number }}
</div>
<div>
{{ form.work_area.help_text }}
{{ form.work_area }}
</div>
</div>
<div>
<div>
<button type="submit" name="enter_area" value="Enter">Enter Area</button>
</div>
</div>
</form>
<script>
$("#id_employee_number").change(function () {
var employee_number = $(this).val();
var url = $("#warehouseForm").data("employee-name");
$.ajax({
url: url,
type:'GET',
data: {
'id': employee_number
},
success: function (data) {
var employee_name = data['employee_name'];
$('#employee_name').text(employee_name);
},
error : function (data) {
var error_message = data['error'];
$('#employee_name').text(error_message);
}
});
});
</script>
{% endblock main %}
What could be causing nothing to render on the page? Is there a call missing in the html portion? I don't know if <h1 id="employee_name">{{ employee_name }}</h1> is the proper way to call the function for display. I'm not getting any errors as it does not seem to be getting called at all whatsoever.
Is there a better/more efficient way to accomplish this type of call?
Maybe I'm late, but here's the answer:
I would use GET instead of POST as you are only retrieving data from the url.
views.py
def get_employee_name(request, employee_number):
try:
employee = models.Salesman.objects.get(id=employee_number)
except models.Salesman.DoesNotExist:
return JsonResponse({'error': 'Employee not found'}, status=404)
employee_name = employee.slsmn_name
return JsonResponse({'employee_name': employee_name})
urls.py
app_name = 'operations'
urlpatterns = [
path('enter-exit-area/', views.enter_exit_area, name='enter_exit_area'),
path('get-employee-name/<int:employee_number>',
views.get_employee_name,
name='get_employee_name'
),
]
enter_exit_area.html
{% extends "operations/base.html" %}
{% block main %}
<form id="warehouseForm" action="" method="POST" novalidate >
{% csrf_token %}
<div>
<h1 id="employee_name"></h1>
<div>
{{ form.employee_number.help_text }}
{{ form.employee_number }}
</div>
<div>
{{ form.work_area.help_text }}
{{ form.work_area }}
</div>
</div>
<div>
<div>
<button type="submit" name="enter_area" value="Enter">Enter Area</button>
</div>
</div>
</form>
<script>
$("#id_employee_number").change(function () {
var employee_number = $(this).val() || 0;
var url = "{% url 'operations:get_employee_name' 0 %}".replace('0', employee_number);
console.log(url);
$.ajax({
url: url,//your url was incorrect
type:'GET',
success: function (data) {
var employee_name = data['employee_name'];
$('#employee_name').text(employee_name);
},
error: function (jqXHR, textStatus, errorThrown) {
$('#employee_name').text(jqXHR.responseJSON.error);
}
});
});
</script>
{% endblock main %}
P.S. You have to define app_name in app's urls.py.
I would like to be able to use my external app data on django cms page.
I am able to use custom plugin data but not data from normal django app
I tried creating views to handle my data but how do I call this view from django cms pages?
here is exactly what I am asking for but his explanation is shallow and the link provided in the answer is no longer in use.
Here is my model:
class ExternalArticle(models.Model):
url = models.URLField()
source = models.CharField(
max_length=100,
help_text="Please supply the source of the article",
verbose_name="source of the article",
)
title = models.CharField(
max_length=250,
help_text="Please supply the title of the article",
verbose_name="title of the article",
)
class Meta:
ordering = ["-original_publication_date"]
def __str__(self):
return u"%s:%s" % (self.source[0:60], self.title[0:60])
My template has placeholders
{% load cms_tags %}
{% block title %}{% page_attribute "page_title" %}{% endblock title %}
{% block content %}
<section class="section">
<div class="container">
<div class="row">
<!-- header-->
<div class="col-lg-12">
<div class="updates">
{% placeholder "header" %}
</div>
</div>
<!-- header end-->
</div> <!-- end row -->
but I don't mind displaying this data anywhere on the template if not possible inside a place holder
I have a custom page that I am using in Django cms.
I would like to display the above data is a section in the Django cms page
If this model was inheriting from CMSPlugin then that would be easy because I could use a custom plugin in my placeholder
I expect to display the data from my model in the template.
I was able to achieve this by doing the following:
#plugin_pool.register_plugin
class ArticlesPluginPublisher(CMSPluginBase):
model = ArticlesPluginModel
name = _("Articles")
render_template = "article_plugin/articles.html"
cache = False
def render(self, context, instance, placeholder):
context = super(ArticlesPluginPublisher, self).render(
context, instance, placeholder
)
context.update(
{
"articles": Article.objects.order_by(
"-original_publication_date"
)
}
)
return context
The plugin model(ArticlesPluginModel) is just for storing the configurations for the instance of the plugin. Not the actual articles.
Then the render will just add to the context the relevant articles from the external app(Article)
You must somehow connect the ExternalArticle with a page object. For example
by defining the ExternalArticle as a page extension
or with an AppHook
or - low-tech - with a PageField on the ExternalArticle model
{% load cms_tags %}
<h1>{{ instance.poll.question }}</h1>
<form action="{% url polls.views.vote poll.id %}" method="post"> {% csrf_token %}
{% for choice in instance.poll.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>
Using django_filter and datetimeinput as a datepicker, I am trying to add a date and time input, a FROM, and TO fields.
I have only been able to use a dateinput with just one field from django forms or from django filter DateTimeFromToRangeFilter without the date picker showing (just manual text entry).
Here is my filter_model.py for the one field with a date picker.
from app.models.api_status import ApiStatus
import django_filters
from django import forms
class DateTimeInput(forms.DateTimeInput):
input_type = 'date'
# working solution for just 1 date field
class ApiStatusFilter(django_filters.FilterSet):
date_time = django_filters.DateFilter(
label=('With start date'),
lookup_expr=('icontains'), # use contains,
widget=DateTimeInput()
)
class Meta:
model = ApiStatus
fields = ['id', 'date_time']
Picture shows a clickable date picker popup.
Here is my filter_model.py for the two fields, FROM and TO without a date picker.
from app.models.api_status import ApiStatus
import django_filters
from django import forms
class DateTimeInput(forms.DateTimeInput):
input_type = 'date'
class ApiStatusFilter(django_filters.FilterSet):
date_time =django_filters.DateTimeFromToRangeFilter()
class Meta:
model = ApiStatus
fields = ['id', 'date_time']
widgets = {
'date_time': forms.DateTimeInput(attrs={'placeholder':'Select a date'})
}
Picture below shows a manual text input without a datepicker popup.
Here is my template file although I didn't alter it much when trying the two approaches above.
status_template.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="{% static 'css/table_styling.css' %}">
<meta charset="UTF-8">
<title>Test Site</title>
{% comment %}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
{% endcomment %}
</head>
<body>
<table>
<thead>
<tr>
{% for keys in dictionarys.keys %}
<th>{{ keys }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
<form method="get">
{{ apistatus_filter.form.as_p }}
<button type="submit">Search</button>
{% for user in dataqs.object_list %}
<tr>
<td>{{ user.id }}</td>
<td>{{ user.date_time }}</td>
{% endfor %}
</form>
</tbody>
</table>
{% comment %} <script>
$( function() {
$("#datepicker").datepicker();
} );
</script> {% endcomment %}
</body>
</html>
I did look into a variety of sources on here and elsewhere. I tried using MultiWidget and jQuery but didn't get those working yet. Thoughts? Thanks in advance.
It's possible to use javascript to make the range fields have a datepicker class.
I was struggling to get a jQuery datepicker to work with the DateTimeFromToRangeFilter from Django Filters combined with the RangeWidget. For some reason it seems like the RangeWidget won't accept class: datepicker.
Filters.py:
dtoriginal = django_filters.DateTimeFromToRangeFilter(lookup_expr='icontains',
widget=django_filters.widgets.RangeWidget(
attrs={
'placeholder': 'yyyy-mm-dd',
},
),
label = 'Date Original'
)
I changed my search template html to include the following script:
<form method="get">
{{ filter.form.as_p }}
<script>
$(function () {
$("id_dtoriginal_0").datepicker();
$("id_dtoriginal_1").datepicker();
});
</script>
{% if filter.is_bound %}
<button onclick=...></button
{% endif %}
</form>
Where dtoriginal is the name of the field in the model. _0 and _1 are the "from" and "to" fields created by RangeWidget.
Hopefully this helps, I spent hours trying to figure it out how to do it through django-filters, with no luck.
I was able to solve it using no external dependencies (no jquery), just used datetime-local input and DateTimeFromToRangeFilter with Range widget. Perhaps not the most ideal solution, but it is one way to do this.
My model, filter, view, and template codes are below.
model.py
from app.modules.string_handler import StringHandler
from django.db.models.signals import post_save
import datetime
class ApiStatus(models.Model):
id = models.AutoField(primary_key=True)
date_time = models.DateTimeField("Date_Time", default=datetime.datetime.now(), blank=True)
class Meta:
managed = True
db_table = 'api_status'
verbose_name = 'API STATUS'
def __str__(self):
"A string representation of the model."
return f'{self.id},{self.token},{self.date_time},{self.status},{self.summary},{self.log}'
def __unicode__(self):
return self.created_at
filter.py
from app.models.api_status import ApiStatus
import django_filters
from django import forms
class ApiStatusFilter(django_filters.FilterSet):
date_time = django_filters.DateTimeFromToRangeFilter(
lookup_expr=('icontains'),
widget=django_filters.widgets.RangeWidget(
attrs={'type':'datetime-local'}
)
)
class Meta:
model = ApiStatus
fields = ['id', 'date_time']
view.py
from django.shortcuts import render
from app.models.filters_model import ApiStatusFilter
from app.models.api_status import ApiStatus
import requests
from django import forms
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
import urllib
from datetime import datetime, timedelta
def status(request):
apistatus_list = ApiStatus.objects.all()
request.GET2 = request.GET.copy()
if request.GET2.get('date_time_min'):
request.GET2['date_time_min'] = datetime.strptime(request.GET2['date_time_min'],"%Y-%m-%dT%H:%M").strftime("%Y-%m-%d %H:%M")
if request.GET2.get('date_time_max'):
request.GET2['date_time_max'] = datetime.strptime(request.GET2['date_time_max'],"%Y-%m-%dT%H:%M").strftime("%Y-%m-%d %H:%M")
apistatus_filter = ApiStatusFilter(request.GET2, queryset=apistatus_list)
paginator = Paginator(apistatus_filter.qs, 10)
page = request.GET.get('page')
try:
dataqs = paginator.page(page)
except PageNotAnInteger:
dataqs = paginator.page(1)
except EmptyPage:
dataqs = paginator.page(paginator.num_pages)
return render(request, 'status_page_template.html', {'table_col_DATA':all_entries_ordered, 'dictionarys': dictionarys, 'apistatus_filter': apistatus_filter, 'dataqs': dataqs, 'allobjects': apistatus_list})
template.html
{% load my_templatetags %}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="{% static 'css/search_form_table_styling.css' %}">
<meta charset="UTF-8">
<title>TEST Site</title>
</head>
<body>
<form method="get" action="">
<div class="search_form_wrapper">
<div class="id_box">ID:{{ apistatus_filter.form.id }}</div>
<div class="id_box">Date_Time:{{ apistatus_filter.form.date_time }}</div>
</div>
<input type="submit" value="Submit" class="search_form_submit">
</form>
<table>
<tbody>
{% for user in dataqs.object_list %}
<tr>
<td>{{ user.id }}</td>
<td>{{ user.date_time }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="pagination">
<span>
{% if dataqs.has_previous %}
« first
previous
{% endif %}
<span class="current">
Page {{ dataqs.number }} of {{ dataqs.paginator.num_pages }}.
</span>
{% if dataqs.has_next %}
next
last »
{% endif %}
</span>
</div>
</body>
</html>