How to pass a Javascript variable in django template-tag
Hello i have this question
if have a variable
<script>
var a = True
<script>
can i use the variable like
{% if a %}
<h1> True</h1>
{%else%}
<h1> False </h1>
{%endif%}
The both pieces of code are in the same page
I don't want to use filters it will complicate a lot my work Thank you
2 answers
-
answered 2018-07-12 07:45
Adelin
No, you can't. For Django,
var a = True
is just a string.Django is the one that creates the HTML and tells the browser what strings to use, and the browser will interpret the string and find it to be JavaScript, so it'll execute and finally see that
a
is a boolean.By the time it does that, Django is long gone
The only way you can tell django to use
a
as a boolean, is to make another request to the server, sendinga
as a JSON or querystring parameter, and later interpret the request from python/django and use it in templates. (quite a costly task) -
answered 2018-07-12 07:55
Rakesh
You can do the html modification in JavaScript
Ex:
<script> var a = true; if (a){ document.getElementById("your_h2_tag_ID").innerHTML = "True"; }else{ document.getElementById("your_h2_tag_ID").innerHTML = "False"; } <script>
See also questions close to this topic
-
How can i block some character in textarea with VueJs
I have a textarea for sending messages and i wanna block email and site links. So when i write a @ or https:// must shown error messages using v-if. but how can i do this? which functions?
new Vue({ el: "#app", data: { message: { content: "" } }, })
body { background: #20262E; padding: 20px; font-family: Helvetica; } #app { background: #fff; border-radius: 4px; padding: 20px; transition: all 0.2s; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <div> <textarea v-bind="message" v-model="message.content" cols="30" rows="10"> </textarea> <p v-if="message.content == '@'"> No special characters </p> </div> </div>
-
Why does jQuery's ajax success method doesn't work?
I am trying to add some animation while a type-file input is processing the file, I decided to use jQUery's ajax method to send the form data.
I noticed that the
beforeSend
method works, but not with thesuccess
method, but instead, theerror
method contains all the response sent by my node server. I tried looking for similiar question but none of them work for me.JS:
fileForm.on('submit', function(e) { e.preventDefault(); let formData = new FormData(); formData.append('file', $('#input-file').prop('files')[0]); $.ajax({ url: this.action, dataType: 'script', cache: false, contentType: false, processData: false, beforeSend: () => { console.log('loading'); }, success: function(response) { console.log(response); // Not logging anything setTimeout(() => { console.log('succeded: ' + response); }, 500); }, error: (err) => { console.log(err); // This logs the response }, data: formData, type: this.method.toUpperCase() }); });
Node.JS:
router.post('/image', upload.single('file'), async (req, res) => { if (req.session.passport !== undefined) { try { console.log(req.file, req.body); const query = {_id: req.session.passport.user}; const user = await modelAct(userModel, query, 'findOne'); // const opt = { // query: query, // data: { // $set: { // avatar_path: req.file.path // } // } // }; // await modelAct(userModel, opt, 'updateOne'); res.status(200).json({fileData: req.file}); } catch(err) { console.log(err); if ((typeof err.message == 'string')) { res.sendStatus(err.message); } else { res.sendStatus(500); } } } else { res.sendStatus(401); } });
-
vee-validate dose not change language
hello i try to change the message error in vee validate and it's dosen't work...
some one know how to fix that??
import VeeValidate from "vee-validate"; import hebrew from "vee-validate/dist/locale/he"; Vue.use(VeeValidate, { locale: "he", dictionary: { he: { messages: hebrew } } });
Thanks!!!
-
translation not working in Django 1.5 even after compiling message
I'm using Django 1.5
I have to enable internationalization in my application. For that, I have added a few things to the settings.py file
MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ... ) from django.conf import global_settings TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + ( '...local context processrors...' ) # global_settings.TEMPLATE_CONTEXT_PROCESSORS contains # TEMPLATE_CONTEXT_PROCESSORS = ( # 'django.contrib.auth.context_processors.auth', # 'django.core.context_processors.debug', # 'django.core.context_processors.i18n', # ... # ) USE_I18N = True USE_L10N = True LANGUAGE_CODE = 'es' # List of languages available for translation ugettext = lambda s: s LANGUAGES = ( ('en', ugettext('English')), ('es', ugettext('Spanish')) ) LOCALE_PATHS = ( os.path.join(PROJECT_ROOT, 'locale/'), )
The LOCALE_PATHS has the location output as
('/media/path_to_project/workbench/workbench/settings/../locale/',)
But on running
./manage.py makemessages -l es
it generates *.po file in/media/path_to_project/workbench/workbench
instead of
/media/path_to_project/workbench/workbench/locale
Also, the compiled language is not showing in the template.
-
Cannot get last n elements from GraphQL with graphene_django
I was trying to implement GraphQL in existing Django REST Framework. I used graphene-django==2.2.0
It was successfully implemented. But cannot use 'last' keyword in the request query. I am adding the schema code.
import graphene from graphene_django.types import DjangoObjectType from flowers.models import Flower class FlowerType(DjangoObjectType): class Meta: model = Flower class Query(graphene.ObjectType): flowers = graphene.List(FlowerType) def resolve_flowers(self, info, **kwargs): return Flower.objects.all()
Query
{ flowers (last: 2){ id } }
Result
{ "errors": [ { "locations": [ { "column": 12, "line": 2 } ], "message": "Unknown argument \"last\" on field \"flowers\" of type \"Query\"." } ] }
Do I have to modify the code in Django project? How to resolve it?
-
django select only specific fields from many to many field in serializer
My models:
class RequisiteItem(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) enrollable = models.ForeignKey(Enrollable, on_delete=models.CASCADE) created_by = models.ForeignKey(ElsUser, on_delete=models.CASCADE) completed_within_days = models.IntegerField() date_completed_by = models.DateTimeField(default=now, editable=False) class Requisite(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(default=None, blank=True, null=True, max_length=255) description = models.CharField(default=None, blank=True, null=True, max_length=255) items = models.ManyToManyField(RequisiteItem, blank=True) enrolments = models.ManyToManyField(Enrollee, blank=True) created_by = models.ForeignKey(ElsUser, on_delete=models.CASCADE, related_name="requisites", default=None) timestamp = models.DateTimeField(default=now, editable=False) @property def created_by_user(self): return self.created_by.username
Serializer class:
class RequisiteSerializer(serializers.ModelSerializer): created_by = serializers.CharField(source='created_by_user') class Meta: model = Requisite fields = ('id', 'name', 'description', 'items', 'enrolments', 'created_by', 'timestamp') read_only_fields = ['id'] depth = 1
I have enrolments ,created by,requisite items which are foreign keys and manytomany fields etc .In my list API i want only specific fileds from the foreign key to be displayed. For example in the created by field, Elsuser is a custom user inheriting from AbstractUser . I want only the username and email fields from this model and not the entire fields. Similar case for the manyto many fields . How do i implement this?
-
How to map a dataframe df (having two columns) with another dataframe df1(having three columns) and update it
have a df1 with values
0 1 0 abc def unknown 1 uvw xyz unknown 2 cricket ball unknown 3 tennis racket unknown
And df2 with values
0 0 1 0 abc def password 1 cricket ball password1 2 tennis racket password2 ---------- ---------- ---------- 22600 uvw xyz password3
should map the df1 and df2 with 0 values and update 1 column in df1
Output should be
0 1 0 abc def | password 1 uvw xyz | password3 2 cricket ball | password1 3 tennis racket | password2
-
bash: cookiecutter: command not found (cookiecutter installed using conda)
I have installed python cookiecutter using conda:
conda config --add channels conda-forge conda install coockiecutter
In anaconda prompt "
cookiecutter --version
" shows "1.6.0 fromd:\users\username\appdata\local\continuum\anaconda3\lib\site-packages
.Upon running
cookiecutter
command ingit bash
and it gives an error "bash: cookiecutter: command not found
".I have already added the path where
cookiecutter
is installed in windows environment variable "path".
Could you please suggest me how to resolve this issue? -
Relative XPath Wrongly Selects Same Element in Loop
I'm scraping some data.
One of the data points I need is the date, but the table cells containing this data only include months and days. Luckily the year is used to categorize the tables.
Actual Output
For some reason the following code is selecting the same
preceding-sibling::(h3 or h2)/span).text
element for every iteration.# random, hypothetical values Page #1 element="921" element="921" element="921" ... Page #2 element="1283" element="1283" element="1283" ...
Expected Output
I would expect the following script to select the unique
preceding-sibling::/span).text
element relative to each//h2/following::table
element as it loops through all of them, but this isn't the case.# random, hypothetical values Page #1 element="921" element="922" element="923" ... Page #2 element="1283" element="1284" element="1285" ...
How come the following code selects the same element for every iteration on each page?
# -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver import Firefox from selenium.webdriver.common.by import By links_sc2 = [ 'https://liquipedia.net/starcraft2/Premier_Tournaments', 'https://liquipedia.net/starcraft2/Major_Tournaments', 'https://liquipedia.net/starcraft2/Minor_Tournaments', 'https://liquipedia.net/starcraft2/Minor_Tournaments/HotS', 'https://liquipedia.net/starcraft2/Minor_Tournaments/WoL' ] ff = webdriver.Firefox(executable_path=r'C:\\WebDriver\\geckodriver.exe') urls = [] for link in links_sc2: tables = ff.find_elements(By.XPATH, '//h2/following::table') for table in tables: try: # premier, major year = table.find_element(By.XPATH, './preceding-sibling::h3/span').text except: # minor year = table.find_element(By.XPATH, './preceding-sibling::h2/span').text print(year) ff.quit()
-
jQuery "error: can't read property of split of undefined"?
I have an HTML page that has
<select>
inputs that are dynamically made with Django Templates. I need to loop through these<select>
elements with a$('.select_input).each
loop, but I can't seem to get it to work.filters = [(0, 'foo'), ('1', a, '10'), ('2', b, '11') (0, 'bar'), (3, c, '12'), ('4', d, '13') ... ]
myPage.html:
<form method="POST" action="/" id="myform"> <input type="submit" id="search"> {% for f in filters %} {% if f.0 == 0 %} </select> <input type="hidden" id="{{'input_'|add:f.1 }}" name="{{ f.1 }}"> <select id="{{ select_|add.1 }}" class="selectpicker select_input" multiple data-selected-text-format="count" data-style="btn-info" title="{{ f.1 }}"> {% elif f.0 != 0 %} <option value="{{ f.2 }}">f.1</option> {% endif %} {% endfor %} </select> </form>
myPage.js:
When I try this, it seems to work:
$(#search).on('click', function() { $('.select_input').each(function() { var elem = $(this).attr('id'); console.log(elem);//prints select_foo }); });
But as soon as I try to do anything to the
$('.select_input)
, other thanconsole.log
, it stops working.$(#search).on('click', function() { $('.select_input').each(function() { var elem = $(this).attr('id'); //prints undefined console.log(elem); var t = elem.split('_'); //error: cannot read property split of undefined var t = elem.toString; //error: cannot read property toString of undefined }); });
What am I missing here?
Note: I realize that there will be an additional
</select>
at the beginning of the loop, but I don't think that matters and I don't know how to make this loop work otherwise.I checked the HTML before and after the changes to
myPage.js
and it seems that they are identical, yet theconsole.log
still only works on the firstmyPage.js
example. -
How do I iterate through a dictionary in Django Templates?
I am trying to iterate through a dictionary in my django template and save the values to
window.obj
, but it is not working.views.py:
def myView(req): ... myDict = {'foo':"[1,2]", 'bar':"[3,4]"} return render(req, 'myPage.html', {'myDict':myDict})
myPage.html:
<script type="text/javascript"> window.obj = {} window.obj["foo"] = "{{ myDict.foo }}"; {% for key, value in myDict %} window.obj["{{ key }}"] = "{{ value }}"; {% endfor %} </script> ... <script> console.log(window.obj.foo); //prints {foo: "[1,2]"} console.log(window.obj.bar); //prints undefined </script>
Note: I can't use
myDict.foo
on my actual projectWhat am I missing here?
-
Django showing values of an annotated queryset without knowing the filed name
I´m building a dashboard where you can cross data from a sales database.
For example, sales by seller, products by client, etc. I let the user choose both option 1 and option 2.
I get the form back to the view and annotate the model with those options:
if filter_opts.is_valid(): option_1 = filter_opts.cleaned_data["option_1"] option_2 = filter_opts.cleaned_data["option_2"] results = ventas.values(option_2).annotate(Count(option_1, distinct=True))
The annotation works fine and if I just print the queryset in the template
{% for case in results %} {{ case }} {% endfor %}
I can see it like:
{'cliente': '502 EMSUR', 'prod_nombre__count': 9}
Then in the template I want to show only the values. But I can´t tell forehand which would be the value name to do something like this:
{% for case in results %} {{ case.option_1 }} {{ case.option_2 }} {% endfor %}
If I iterate over the result I can see the field name:
{% for case in results %} {% for item in case %} {{ item }} {% endfor %} {% endfor %}
How can I show the values of that fields?
Thanks!