datepicker Is not showing? - django

I am developing an application with Django and I need to choose date and time. I am trying to do it with 'bootstrap_datepicker_plus', but the calendar does not appear when I show the form.
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'hungryFalconryApp',
'rest_framework',
'bootstrap4',
'bootstrap_datepicker_plus',
]
BOOTSTRAP4 = {
'include_jquery': True,
}
forms.py
from django import forms
from bootstrap_datepicker_plus import DateTimePickerInput
class DateForm(forms.ModelForm):
class Meta:
model = Comedero
fields = ('dias', 'horas')
widgets = {
'dias': DateTimePickerInput(),
'horas': DateTimePickerInput(),
}
views.py
def programar_comederos(request, nombre):
if request.method == "POST":
form = DateForm(request.POST)
print(nombre)
if(form.is_valid()):
comedero = form.save(commit=False)
print(comedero.dias)
print(comedero.horas)
else:
form = DateForm()
return render(request, 'hungryFalconryApp/programar_comederos.html',{'nombre': nombre, 'form':form})
template.html
{% load bootstrap4 %}
{% bootstrap_css %}
{% bootstrap_javascript jquery='full' %}
{% bootstrap_messages %}
{{ form.media }}
{% block content %}
<form action="" method="post" class="form">
{% csrf_token %}
{% bootstrap_form form %}
{% bootstrap_button "Guardar" button_type="submit" button_class="btn-primary" %}
</form>
{% endblock %}

I have already solved. In django-bootstrap-datepicker-plus it indicates putting {{form.media}} after this code but {{form.media}} must go inside the tag

you can also use Datepicker too, Datepicker is jqueryUI, its faster and also reliable
see example here
you just cdn or jqueryUI file in your project
jqueryUI CDN
<script
src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"
integrity="sha256-0YPKAwZP7Mp3ALMRVB2i8GXeEndvCq3eSl/WsAl1Ryk="
crossorigin="anonymous"></script>
then assign Id to that particular field
<script>
$("#datepicker").datepicker({ dateFormat: 'dd M yy' });
</script>
" datepicker " is html id you also change date format from dateFormat

Related

Add link on a web page to export tables2 data in Django

I'm trying to include a link on a webpage to download a tables2 table to csv. I got the commented out piece below from the documentation, and I think it might just need a simple tweak to get it to work with my code. Any thoughts?
views.py
class PlatListView(SingleTableMixin, FilterView):
model = Plat
template_name = 'blog/filtertable.html'
filter_class = PlatFilter
def get_context_data(self, **kwargs):
context = super(PlatListView, self).get_context_data(**kwargs)
query = Phase.objects.all().select_related('plat','plat__community')
f = PlatFilter(self.request.GET, queryset=query)
t = PlatTable(data = f.qs)
RequestConfig(self.request, paginate=False).configure(t)
context['filter'] = f
context['table'] = t
'''
export_format = self.request.GET.get("_export", None)
if TableExport.is_valid_format(export_format):
exporter = TableExport(export_format, query)
return exporter.response("query.{}".format(export_format))
'''
return context
filtertable.html
{% extends "blog/base.html" %}
{% block content %}
{% load querystring from django_tables2 %}
<div style = 'padding-top: 24px'>
Download CSV
</div>
{% load render_table from django_tables2 %}
{% load bootstrap4 %}
{% if filter %}
<form action="" method="get" class="form form-inline">
{% bootstrap_form filter.form layout='inline' %}
{% bootstrap_button 'filter' %}
</form>
{% endif %}
{% render_table table 'django_tables2/bootstrap4.html' %}
{% endblock content %}
The commented-out snippet in your code is for function-based views as mentioned in the docs. In your case you should just add the ExportMixin :
from django_tables2.export.views import ExportMixin
class PlatListView(SingleTableMixin, ExportMixin, FilterView):
# other stuff your view is doing

How to Create a UpdateForm with TemplateView?

I need to create a UpdateForm with a TemplateView. Why with TemplateView? Because, I has a attribute what is geo_location, and I'm using LeafLet maps, and LeafLet maps doesn't work with generic.UpdateView or others the same type.
Here my views from Update:
class UpdateStore(LoginRequiredMixin, TemplateView):
template_name = 'store_form'
success_url = reverse_lazy('register:store_list')
def post(self, request, *args, **kwargs):
store_id = kwargs['store']
store = get_object_or_404(Store, pk=store_id)
form = StoreForm(request.POST, on_edit=True)
if form.is_valid():
form.save()
return redirect(reverse('register:store_list'))
else:
context = self.get_context_data()
context['data_form'] = form
return render(request, self.template_name, context)
return self.get(request)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
store_id = self.kwargs['store']
store = get_object_or_404(Store, pk=store_id)
data = {
'name': store.name,
'description': store.description,
'address': store.address,
'geo_loc': store.geo_loc,
'opened': store.opened
}
context['editing'] = True
context['data_form'] = StoreForm(initial=data, on_edit=True)
context['store'] = store
return context
Here is my template code:
{% extends 'base.html' %}
{% load bootstrap3 %}
{% load leaflet_tags %}
{% block extra_css %}
{% leaflet_css plugins="forms" %}
{% endblock %}
{% block body %}
<h1> Update Store </h1>
<form method="POST">
{% csrf_token %}
{{ form }}
{% buttons %}
<button type="submit">
{% bootstrap_icon "star" %} Save
</button>
{% endbuttons %}
</form>
{% endblock %}
{% block extra_js %}
{% leaflet_js plugins="forms" %}
{% endblock %}
I trying this, but in my template, the Forms doesn't load, and my template are blanked :(. Someone knows why? I need another method for get anything else?
Thanks.
The problem with your code is that you place the form in the data_form key of the context:
context['data_form'] = StoreForm(initial=data, on_edit=True)
and then on the template you try to use it with {{form}} instead of {{data_form}}. After that the form should be rendered.

templatetag: QuerySet' object has no attribute 'getlist'

I'm greeted with the following error when attempting to follow a books example of templatetags with modification:
QuerySet' object has no attribute 'getlist'report_id=88&report_id=89 HTTP/1.1" 500 180158
I'm following the instructions of adding templatetags to my app directory and included the init.py and the app_filter.py i'd like to filter on, as such:
Security
accounts
templatetags
app_filters.py
__init__.py
My app_filter.py is defined as such:
from django import template
register = template.Library()
#register.filter
def get_list(querydict, itemToGet ):
return querydict.getlist(itemToGet)
My settings.py includes the following:
INSTALLED_APPS = [
'django_python3_ldap',
'django_extensions',
'django_filters',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts',
]
My view is passing the array correctly:
checked = request.GET.get('report_id')
checkedlist = request.GET.getlist('report_id')
reportlist = QvReportList.objects.filter(report_id__in= checkedlist, active = 1).values_list('report_name_sc',flat = True)
print (checked)
print (checkedlist)
args = {'retreivecheckbox': reportlist}
return render(request,'accounts/requestaccess.html', args)
I see the array in my console, when doing a print checkedlist:
['75', '76', '77']
My template is the following:
{% load app_filters %}
{% for reports in retreivecheckbox %}
{{ retreivecheckbox|get_list:'report_id' }}
</div>
{% endfor %}
You're calling #register.filter with a path. I think you mean to call it with #register.filter('get_list')
Take a look at the docs: these are the two use examples:
#register.filter(name='cut')
def cut(value, arg):
return value.replace(arg, '')
#register.filter
def lower(value):
return value.lower()
Those would create two filters, lower and cut.
Alternatively, you can call #register.filter and pass the name as the first parameter, as in these cases:
register.filter('cut', cut)
register.filter('lower', lower)
I had to use {{ retreivecheckbox|get_list:report_id }}
and not {{ retreivecheckbox|get_list:'report_id' }}
{% load app_filters %}
{% for reports in retreivecheckbox %}
{{ retreivecheckbox|get_list:report_name_sc }}
</div>
{% endfor %}

Django 1.5 Creating multiple instances of model in ModelAdmin

I'm kind of puzzled with this task:
I have 2 tables: User, Codes
I want to generate randomly codes in a specific pattern.
I've already written that part as a function, but it's hard to implement the function
in the ModelAdmin.
So I would be very pleased if someone knows a trick to accomplish this.
It would be enough to have a button in the User form to envoke the function, which then creates these codes.
But how do I implement such a button?
Is there a way to to this?
EDIT: typo
SOLUTION:
Since I want to generate vouchers for a particular user I can edit the admin.py like this:
class MyUserAdmin(UserAdmin):
def vouchers(self, obj):
return "<a href='%s'>Generate vouchers</a>" % reverse(gen_voucher_view, kwargs={'user':obj.pk,})
vouchers.allow_tags = True
list_display = (..., 'vouchers')
which represents a clickable link in the admin view of my User model.
Now I connect the link to my view in urls.py by adding
url(r'admin/gen_vouchers/(?P<user>\w+)/$', gen_voucher_view, name='gen_voucher_view')
to urlpatterns.
For creating the vouchers I provide a form in forms.py
class VoucherGeneratorForm(forms.Form):
user = forms.CharField(User, required=True, widget=forms.HiddenInput())
amount = forms.IntegerField(min_value=0, max_value=500, required=True)
readonly = ('user', )
In views.py I'm adding my view function:
#login_required
def gen_voucher_view(request, user):
if request.method == 'POST': # If the form has been submitted...
form = VoucherGeneratorForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# GENERATE vouchers here by using form.cleaned_data['amount']
# and user (generate_vouchers is a self defined function)
vouchers = generate_vouchers(user, form.cleaned_data['amount']
# set error or info message
if len(vouchers) == form.cleaned_data['amount']:
messages.info(request, "Successfully generated %d voucher codes for %s" % (form.cleaned_data['amount'], user))
else:
messages.error(request, "Something went wrong")
u = User.objects.get(pk=user)
form = VoucherGeneratorForm(initial={'user':user}) # An unbound form
return render_to_response('admin/codes.html', {'request': request, 'user':user, 'form':form, 'userobj': u}, context_instance=RequestContext(request))
else:
form = VoucherGeneratorForm(initial={'user':user}) # An unbound form
Last but not least create a template admin/codes.html where my form is displayed:
{% extends "admin/base_site.html" %}
{% load i18n admin_static static %}
{% block breadcrumbs %}
<div class="breadcrumbs">
{% trans 'Home' %}
›
{% trans 'Users' %}
›
{% trans 'Vouchercodes' %}
›
Voucher Generator
</div>
{% endblock %}
{% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% static "admin/css/dashboard.css" %}" />{% endblock %}
{% block content %}
<div id="content-main">
{% if request.user.is_active and request.user.is_staff or userobj and userobj.is_active and userobj.is_staff %}
<h1 id="generator_title">Generate vouchers for {{user}}</h1>
<form id="formular_generator" action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<table>{{ form }}</table>
<button id="generatebutton" type="submit" name="action" value="generate">Generate</input>
</form>
{% else %}
<p>{% trans "You don't have permission to access this site." %}</p>
</div>
{% endif %}
{% endblock %}
{% block sidebar %}
{% endblock %}
Done!
To export them in a pdf I used admin actions, as propsed by Sumeet Dhariwal below.
U mean that you need to run a script from within the admin ?
If so check out django-admin-tools
http://django-admin-tools.readthedocs.org/en/latest/dashboard.html
SOLUTION FOUND:
no that was not what i meant, because I want to generate vouchers for 1 particular user and not for more, but that's a good remark.

django allAuth 'request' error when using provider_login_url in e.g. main.html

Afraid this is a newbie question.
I'm trying to have social login links on my main page, using this code in my template:
{% load i18n %}
{% load static %}
{% load socialaccount %}
{% load account %}
{% load url from future %}
{% get_static_prefix as STATIC_PREFIX %}
...
<img src='{{ STATIC_PREFIX }}img/facebookText.png' alt="facebook connect">
<img src='{{ STATIC_PREFIX }}img/googleText.png' alt="google connect">
<img src='{{ STATIC_PREFIX }}img/idText.png' alt="Regular login">
I have made sure that my site id is correctly specified (as explained [here][1]).
I have specified settings in my settings.py as suggested in this [tutorial][2] and this [guide][3]:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'django_tables2_reports',
'subscription',
'django_tables2',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook',
'allauth.socialaccount.providers.google',
#'allauth.socialaccount.providers.linkedin',
#'allauth.socialaccount.providers.openid',
# 'allauth.socialaccount.providers.twitter',
'django.contrib.admin',
)
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.request",
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.static',
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"allauth.account.context_processors.account",
"allauth.socialaccount.context_processors.socialaccount",
)
AUTHENTICATION_BACKENDS = (
# Needed to login by username in Django admin, regardless of `allauth`
"django.contrib.auth.backends.ModelBackend",
# `allauth` specific authentication methods, such as login by e-mail
"allauth.account.auth_backends.AuthenticationBackend",
)
I also specified that after logging in, the user is directed to my homepage:
LOGIN_REDIRECT_URL="/"
But I get this error when accessing my home page (the page supplied with the far above template):
Error during template rendering
In template C:\Users\Andy\Desktop\business\app\static\templates\base.html, error at line 40
request
30 </style>
31 </head>
32 <body class="{% block body_class %}{% endblock %}">
33 <div align="right">
34 {% if user.is_authenticated %}
35 {% user_display user as user_display %}
36 {% blocktrans %}{{ user_display }} logged in{% endblocktrans %}
37 Sign Out
38 {% else %}
39 <img src='{{ STATIC_PREFIX }}img/loginText.png' alt="login">
40 <img src='{{ STATIC_PREFIX }}img/facebookText.png' alt="facebook connect">
41 <img src='{{ STATIC_PREFIX }}img/googleText.png' alt="google connect">
42 <img src='{{ STATIC_PREFIX }}img/idText.png' alt="Regular login">
43 {% endif %}
44 </div>
45
46
47
48
49 {% block body %}
50 {% block content %}{% endblock %}
Help would very much be appreciated :) I suspect that my View needs to deliver additional info to my html, related to this provider_login_url .
answering my own silly question,
my main page View was:
def home(request):
"""Main listing."""
return render_to_response("main/index.html", "")
now it is:
def home(request):
"""Main listing."""
return render_to_response("main/index.html", context_instance=RequestContext(request))