codemirror - multiple text areas not working - javascript

As per the question here Can codemirror be used on multiple textareas?.
I have applied the exact config to my page and neither text areas are being converted to code mirrors.
there are no errors in the console either, im not sure what ive missed?
my code is as follows:
<script src="{% static 'home/scripts/codemirror/codemirror.js' %}"></script>
<link href="{% static 'home/scripts/codemirror/codemirror.css' %}" rel="stylesheet">
<script src="{% static 'home/scripts/codemirror/django/django.js' %}"></script>
<script type="text/javascript">
function editor(id) {
CodeMirror.fromTextArea(id, {
height: "400px",
continuousScanning: 500,
lineNumbers: true
});
}
editor('id_config');
editor('id_remote_config');
</script>
<form id="edit_template" action="" method="post">
{% csrf_token %}
{{ TemplateForm.template_name }}
{{ TemplateForm.config }}
{{ TemplateForm.remote_config }}
<input type='submit' value='Update' />
</form>
the django form renders the text areas with the IDs I have specified
anyone have any ideas?
Thanks

Those textareas don't exist at the time you call editor(). Either move your script tag below the form or call editor() inside a window load event handler

Related

Error: Cannot read properties of null reading "checked"

I'm having trouble fully wiring on my Django applications submit button, it seems that the JS function does not understand which checked boxes to look for
all the console returns are "cannot read properties of null, reading "checked" I'm assuming its something with the function defining but I cannot seem to get it working
Heres the code:
<html>
<head>
{% load static%}
{% block content%}
<link rel="shortcut icon" type="image/png" href="{% static 'IMG/favicon.ico' %}"/>
<link rel="stylesheet" href="{% static 'CSS/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'CSS/jquery-ui.css' %}">
<script type="text/javascript" src="{% static 'JS/bootstrap.min.js' %}"></script>
<title>Task List</title>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="{% static 'JS/jquery-ui.min.js' %}"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script>
let _csrf = '{{csrf_token}}';
function submit_delete() {
var listItems = $("#list li input");
var checkedListItems = [];
listItems.each(function() {
if (document.getElementById(this.id).checked) {
checkedListItems.push(getTaskId(this.id));
console.log(checkedListItems);
}
})
$.ajax({
headers: { "X-CSRFToken": _csrf },
type: "POST",
url: "/ptm/item_delete",
data: {
'deleteList[]': checkedListItems
}
}).done(location.reload());
}
function getTaskId(str) {
return str.split('-')[1];
}
</script>
</head>
<body>
<div id="logo" class="border-success border border-3 rounded-2" style="width: 61.rem;">
<div class="card-body">
<img class="card-img" src="{% static '/IMG/Logo.png' %}">
</div>
</div>
<div id="taskList" class="card">
{% if task_list %}
<ul class="list-group" id="list">
{% for item in task_list %}
<li class="list-group-item" id='tdList'>
<input id="check-{{ item.id }}" type="checkbox" class="form-check-input me-1" value="">
<label class='d-flex w-100 justify-content-between'>
<h2 class="form-check-label" for="check-{{ item.id }}">{{ item.title }}</h2>
<small class='text-muted'>{{ item.date }}</small>
<input size='3'>
</label>
<h5 class="form-check-label">{{ item.description }}</h5>
</li>
{% endfor %}
</ul>
{% else %}
<p>There are no current tasks assigned to this department.</p>
{% endif %}
</div>
{% csrf_token %}
<div id="taskEnter" class="card-footer">
<div class="d-grid mx-auto">
{% if task_list %}
<button type="button" onclick="submit_delete()" value='delete' class="btn btn-success btn-lg d-grid" value='delete'><i class="">Submit</i></button>
{% endif %}
</div>
</div>
</body>
{% endblock %}
</html>
In the part:
document.getElementById(this.id).checked
document.getElementById(this.id) evaluates to null, which doesn't have any properties, hence the exception you're getting. You're effectively doing null.checked which won't work.
It looks like you're trying to iterate over the checkboxes and determine whether they're checked or not. I'm reasonably confident that this inside the function you wrote will just refer to the window object, so calling this.id won't give you a checkbox id. You have actually already fetched all of the checkboxes (you're iterating over them!) so there's no need to refetch each one manually. Just do:
listItems.each(function(listItem) {
if (listItem.checked) {
checkedListItems.push(getTaskId(listItem.id));
console.log(checkedListItems);
}
})
Note that the function takes as argument the individual listItem (confusingly named since they're actually checkboxes but I'm following your nomenclature here) that each is currently iterating over. Which is what you need.
Try adding a child combinator ('>') to the element selector used in the first line of function submit_delete:
var listItems = $("#list li > input");
- or use a more precise selector of your own devisement.
As posted there appear to be descendant input elements of .list li of form <input size='3'> that don't have an id attribute. Processing these in each returns null from getElementById and throws the error that checked can't be a property of null.
About each
JAuery's each function fires its callback with a this value set to the element being processed during the iteration. The element is also provided to the callback as its second argument. Given elements in HTML should have unique id values:
For elements referred to by this that have id values, using this for the element is simpler than calling getElementById(this.id).
For elements (referred to by this) that do not have an id, !this.id) is a simpler conditional expression than getElementById(this.id)===null.
Filtering out elements that should not be mnatched during selection is preferable to filtering them out later.

Django-autocomplete-light - "No results found" in browser on startup - after doing one search in admin - results are found in browser again

I have a peculiar problem with Django-autocomplete-light. When I go to my browser and try searching for something I get "no results found" - but when I go to the admin panel and add a model, the results pop up as they should. When I have done this one time, I can go back to the browser and then the results show up as they should. I'm suspecting some caching issue, but not sure how to debug this. Maybe someone can take a look if there is something wrong with my set-up.
models.py
class DogBreeds(models.Model):
name = models.CharField(max_length=150)
def __str__(self):
return self.name
class Advertisement(SoftDeleteModel, TimeStampedModel):
breed = models.ForeignKey(DogBreeds, on_delete=models.CASCADE, null=True, verbose_name='Hundras')
views.py
class BreedAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
if not self.request.user.is_authenticated:
return DogBreeds.objects.none()
qs = DogBreeds.objects.all()
if self.q:
qs = qs.filter(name__icontains=self.q)
return qs
Form template
{% extends '_base.html' %}
{% load static %}
{% block content %}
<form method="post" enctype="multipart/form-data" id="adForm" data-municipalities-url="{% url 'ajax_load_municipalities' %}" data-areas-url="{% url 'ajax_load_areas' %}" novalidate>
{% csrf_token %}
<table>
{{ form.as_p }}
</table>
<button type="submit">Publish</button>
</form>
</body>
{% endblock content %}
{% block footer %}
{% comment %} Imports for managing Django Autocomplete Light in form {% endcomment %}
<script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.js' %}"></script>
<link rel="stylesheet" type="text/css" href="{% static 'autocomplete_light/select2.css' %}" />
<script type="text/javascript" src="{% static 'autocomplete_light/select2.js' %}"></script>
<link rel="stylesheet" type="text/css" href="{% static 'autocomplete_light/vendor/select2/dist/css/select2.css' %}" />
<script type="text/javascript" src="{% static 'autocomplete_light/vendor/select2/dist/js/select2.full.js' %}"></script>
<script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.js' %}"></script>
{{ form.media }}
{% endblock footer %}
Admin.py
class AdvertisementAdmin(admin.ModelAdmin):
form = NewAdTakeMyDogForm
readonly_fields = ('id',)
admin.site.register(Advertisement, AdvertisementAdmin)
The issue was resolved by removing the following lines, as per the recommendation by the good Iain Shelvington!
if not self.request.user.is_authenticated:
return DogBreeds.objects.none()

Panzoom on django with jquery

I have a really basic django app that displays .png images using django ImageField and ask the user to vote on different choices.
Now I need to make it interactive so that the user can also zoom and pan the images in the form.
I've downoad this github https://github.com/timmywil/jquery.panzoom and followed the instructions in my detail view: detail.html :
<div id="img">
<img src="{{question.image.url}}"/>
</div>
{% load static %}
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="{% static 'polls/node_modules/jquery.panzoom/dist/jquery.panzoom.js' %}"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
$("img").panzoom();
$("img").panzoom({ minScale: 0, $zoomRange: $("input[type='range']") });
});
</script>
But nothing happens at all, the image is displayed in a fixed manner.
Previously I had some issues with 404 errors and now It seems to properly load the .js but It still doesn't work.
Thank you in advance for your help.
You have to have:
1) <script type="text/javascript" src="_path_to_your_JS_panzoom_file"></script> - to import that file
2)
<script type="text/javascript">
jQuery(document).ready(function(){
$(".panzoom-elements").panzoom();
// Pass options
$("a.panzoom-elements").panzoom({ minScale: 0, $zoomRange: $("input[type='range']") });
});
</script>
OR 2-b) Add those your code to a separate .js file and import it at the same way as in paragraph 1.
OK, finally I found the problem. The documentation is probably done for people who have a bit more background in that field! But of course other imports are required to make it work:
{% load static %}
<script type="text/javascript" src="{% static 'polls/node_modules/jquery.panzoom/test/libs/jquery.js' %}"></script>
<script type="text/javascript" src="{% static 'polls/node_modules/jquery.panzoom/dist/jquery.panzoom.js' %}"></script>
<script type="text/javascript" src="{% static 'polls/node_modules/jquery.panzoom/test/libs/jquery.mousewheel.js' %}"></script>
<section>
<div class="parent">
<div class="panzoom">
<img src="{{question.image.url}}">
</div>
</div>
<div class="buttons">
<button class="zoom-in">Zoom In</button>
<button class="zoom-out">Zoom Out</button>
<input type="range" class="zoom-range">
<button class="reset">Reset</button>
</div>
<script>
(function() {
var $section = $('section').first();
$section.find('.panzoom').panzoom({
$zoomIn: $section.find(".zoom-in"),
$zoomOut: $section.find(".zoom-out"),
$zoomRange: $section.find(".zoom-range"),
$reset: $section.find(".reset")
});
})();
</script>
</section>

Django, calendar widget doesn't work with ModelForm and Form Media

I found one blog. It explains how apply calendar widget with form media. It is what I exactly want to make. so I followed instructions.
But js and css files doesn't work in widget. I tried to figure out this problem. I spent quite much time by searching and reading stuffs. But I can't get what's wrong in my situation exactly. Well, It could be very easy question but I will appreciate if you can give me any hint to figure out this!
model.py
class Birthday(models.Model):
birthday = models.DateField(null=True)
views.py
def register_birthday(request):
if request.method == 'POST':
form = BirthdayForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/success')
else:
form = BirthdayForm()
return render(request, 'sale/registerbirthday.html', {'form':form})
forms.py
class DateUIWidget(forms.TextInput):
def _media(self):
return forms.Media(css = {
"all": ("tiny-date-picker.css",)
},
js = ("tiny-date-picker.js", "date-init.js",))
media = property(_media)
class BirthdayForm(forms.ModelForm):
class Meta:
model = Birthday
fields = ('birthday',)
widgets = {
"birthday" : DateUIWidget(attrs={'class':'dateuiwidget', 'id':'id_birthday'}),
}
actually I wrote at first like below. but I changed to check if it works when I use media as a dynamic property.
class DateUIWidget(forms.TextInput):
class Media:
css = {
"all": ("tiny-date-picker.css",)
}
js = ("tiny-date-picker.js", "date-init.js",)
forms.py first
<form action="." method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit">
</form>
{{ form.medai}}
I changed it because I read that I should read this when I changed.
As we have already seen, the string representation of a Media object is the HTML required to include the relevant files in the <head> block of your HTML page.
<html>
<head>
{{ form.media }}
</head>
<body>
<form action="." method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit">
</form>
</body>
</html>
under myapp/static/date-init.js
$(".dateuiwidget").each(function(){
return TinyDatePicker(this);
});
I copied two files(tiny-date-picker.js,tiny-date-picker.css) under myapp/static/.
I got two files from here
it shows widget in a form without error. I assume that somehow js, css file didn't apply to this widget.
html source code
<html>
<head>
<link href="/static/tiny-date-picker.css" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/static/tiny-date-picker.js"></script>
<script type="text/javascript" src="/static/date-init.js"></script>
</head>
<body>
<form action="." method="post">
<input type='hidden' name='csrfmiddlewaretoken' value='VC8ahwDLBOsy4IlAzf1iIiukK7ZvTcGDQjL9RxywlauCOX3c8rG7DVJ1ClozHEEW' />
<p><label for="id_birthday">Birthday:</label> <input class="dateuiwidget" id="id_birthday" name="birthday" type="text" required /></p>
<input type="submit">
</form>
</body>
</html>

Dictionary passed to js not working

I am new to javascript. I am working on django project. I need to pass the dictionary template variable to javascript and I have not been able.
views.py includes:
def index(request):
name={'bishal':509,'bishnu':510}
return render_to_response("test.html",Context({'name':simplejson.dumps(name)}))
test.html includes:
{% load staticfiles %}
{% block include_js %}
<script src="{% static "js/chart.js" %}"></script>
<script src="{% static "js/test.js" %}"> </script>
{% endblock include_js %}
{% block main_content %}
<script type="text/javascript" src="static/js/test.js"></script>
<script type="text/javascript">
var name={{name}};
</script>
<button class="btn btn-primary" id="btn1" type="button" onclick="myfunction()">1st visualization</button>
{% endblock %}
test.js includes:
$(function myfunction() {
document.getElementById('btn1').onclick=function(){
name=JSON.parse(name);
alert(name);
};
});
But error occurs saying:
[30/Jul/2013 02:50:51] "GET /visualize/static/js/test.js HTTP/1.1" 404 2732
I tried similar thing in html as:
<html>
<head>
<script type="text/javascript">
function myfunction()
{
dict=JSON.parse(dict);
alert(dict);
}
</script>
</head>
<body>
<script type="text/javascript">
var dict='{"bishnu": 509, "bishal": 510}';
</script>
<form>
<input type="button"
onclick="myfunction()"
value="Call function">
</form>
<p>By pressing the button, a function will be called. The function will alert a message.</p>
</body>
</html>
which worked perfectly. Please help!
Ignore all the JavaScript. The key line in your problem is:
[30/Jul/2013 02:50:51] "GET /visualize/static/js/test.js HTTP/1.1" 404 2732
404 is the HTTP code for 'file not found', which means that you're using the incorrect path to reference your JavaScript file. Fix that, and you may find that your solution then works - or, if not, at least breaks differently.
#Adrian is right about the error message, but I suspect that the problem you're thinking of is caused by not putting quotes around {{name}} in test.html. Try:
<script type="text/javascript">
var name='{{name}}';
</script>

Categories

Resources