how to use VueJs components in Django using django webpack loader? - django

I followed this tutorial and integrated Django and VueJs using django-webpack-loader, now the main.js output from django-webpack-loader is loading to my index.html
This is my project directory structure
- assets
- bundles
- app.js
- js
- components
- Demo.vue
- index.js
- db.sqlite3
- manage.py
- myapp
- myproject
- node_modules
- package.json
- package-lock.json
- requirements.txt
- templates
- webpack.config.js
- webpack-stats.json
My Demo.vue component has been imported to the index.js and using webpack.config.js file all necessary file has been bundled together to app.js.
My question is what is the next step? For example, if I have some VueJs components and want to use them in some of my templates how should I do that? Should I create components in the component directory and bundle them all? If this is the case how should I choose to use or not use a component in a specific template? And how should I use Django template tags to insert dynamic data? Or I should write my components in another way?
I know there is multiple questions here, but I couldn't find a good reference to answer my questions so any help would be appreciated.

Django uses a templating language, called Jinja, to pass context (information) from view to template. Assuming that myapp is a Django app, you should have a myapp/views.py file by default.
In myapp/views.py, you have the ability to create a view (code that is run when a specific URL is accessed). For example, your view could look something like:
from django.shortcuts import render
def my_view(request):
context = {
'my_variable': 'my_variable_value',
}
return render(request, 'template.html', context)
Then, in template.html*, you can use Jinja to parse your context (access my_variable's value). Your template doesn't have to be an HTML file, it can be anything (JS, PHP, etc.), it's just the template file that's loaded from your view.
<html lang="en">
<head></head>
<body>
<h1>{{ my_variable }}</h1>
</body>
</html>
You can use Jinja with Javascript too:
<script>
function test() {
console.log({{ my_variable }});
}
</script>
Jinja supports a variety of functionality, including loops, if blocks, and custom functions (tags). Read more: https://codeburst.io/jinja-2-explained-in-5-minutes-88548486834e
If you're using static files that are NOT in your template file, you'll have to serve them as static files. This is a little more complicated, but not hard! You'll have to use a third party library for serving these files in production, like whitenoise. Here's a great tutorial for Django static files, as this extends past the scope of this question.
*Best practice is to make a directory myapp/templates and put template.html in that directory. Then, point Django to your templates folder in settings.py:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ["myapp/templates"],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

Related

Include a .html file in Django template that is located in a different directory

Let's say I have the following directory structure
|-data
|-include_this.html
|-app
|- templates
|- app
|- page.html
In page.html, I'd like to include the include_this.html file contained in the data folder.
I have tried the following:
{% include '../data/include_this.html' %}
{% include '../../data/include_this.html' %}
{% include './../data/include_this.html' %}
But none of them seem to work, and the second one throws the error: The relative path points outside the file hierarchy that template is in.
Re: #Edoardo Facchinelli suggestions, I've modified settings.py in the following way:
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
TEMPLATES = [{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'data')],
'APP_DIRS': True,
}]
But the include_this.html is still not being recognized.
Running
python manage.py shell
from django.conf import settings
print(settings.TEMPLATES[0]['DIRS'])
Returns:
['_templates']
So it's clearly not adding the data directory specified. What's the correct way to do this?
You need to make sure that the path is known to Django, either as an app, or in this case a template dir. One way to do this is explained here that I think is done well, from that page here's a snippet for the settings.py file, enabling the templates dir.
TEMPLATES = [
{
...
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
...
With other configurations you may need instead the TEMPLATE_DIRS variable, but that will depend on your project, mine use the method in the snippet above.
Once set up, Django will know what data means and you should be able to reference it like so:
{% include 'data/papercups.html' %}

Django 1.10.1 'my_templatetag' is not a registered tag library. Must be one of:

I want a menu thats custom depending which group you are member of.
Im using Django 1.10.1, allauth and so on.
When im trying to make my templatetag it fails and it says:¨
TemplateSyntaxError at /
'my_templatetag' is not a registered tag library. Must be one of:
account
account_tags
admin_list
admin_modify
admin_static
admin_urls
cache
i18n
l10n
log
socialaccount
socialaccount_tags
static
staticfiles
tz
'my_templatetag.py' looks like this:
from django import template
from django.contrib.auth.models import Group
register = template.Library()
#register.filter(name='has_group')
def has_group(user, group_name):
group = Group.objects.get(name=group_name)
return group in user.groups.all()
and tha error comes in my .html file which say,
{% load my_templatetag %}
I have tried to restart the server like millions of times, also i tried to change all the names, and the app is a part of INSTALLED_APPS in settings.py.
What am I doing wrong?
Besides putting my_templatetag.py inside app_name/templatetags, make sure you restart the Django development server (or ensure it restarted itself) every time you modify template tags. If the server does not restart, Django won't register the tags.
From Django 1.9, you can load those new tags/filters in settings like this:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'app.apptemplates.load_setting',
],
'libraries':{
'my_templatetag': 'app.templatetags.my_templatetag',
}
},
},
]
If you have templatetag dir in your project dir (not in an app dir), then above method is recommended.
Example-
Quoting:
https://docs.djangoproject.com/en/3.2/howto/custom-template-tags/#:~:text=It%20also%20enables%20you%20to%20register%20tags%20without%20installing%20an%20application.
Make sure you are not missing any of the following steps:
Create a folder called "templatetags" at the same level as models.py
and views.py in your application folder
Your application must be in the INSTALLED_APPS in settings.py
The templatetags folder must have __init__.py
Restart the django server
In my case the problem was, I was using {% load filter_method_name %}
I had to change to {% load filename %}
I then had to restart the server.
you have to manually stop the development server and start it again,
so Django can identify the new template tags
I am using Django 1.11, and I was having the same problem. Some of the answers here are right, but some things may be missing. Here is what I did:
Quoting a previous user:
Create a folder called "templatetags" at the same level as models.py
and views.py in your application folder
Your application must be in the INSTALLED_APPS in settings.py
The templatetags folder must have init.py
But, before you re-start the Django server, add this to the file that contains the tags:
from django import template
register = template.Library()
Then you can re-start the server.
Where is 'my_templatetag.py' stored? It should be stored in a directory called 'templatetags' which is within the app.
Please see: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/
if that isn't the case.
Restart the django server. It worked for me after setting the templatetag folder within the app and template_name.py in the templatetag folder.
In case it helps someone, the issue in my case was that I was using quotes when trying to load the tag(s)
{% load 'my_templatetag' %} <!-- incorrect -->
instead of
{% load my_templatetag %} <!-- correct -->
Note: extends needs quotes around the filename but not load
I know this is a bit old, but I ran into the same problem today. I found the solution in the docs: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/
The app should contain a templatetags directory, at the same level as models.py, views.py, etc. If this doesn’t already exist, create it - don’t forget the __init__.py file to ensure the directory is treated as a Python package.
Simply copying the __init__.py from another location into the new templatetag's directory sorted it out.
I solved this by adding a templatestag folder in the root with a filter.py file defining my filters, then I adjusted my settings.py.
Please check my complete answer regarding this issue in this similar thread
put my_templatetag.py inside app_name/templatetags then create init.py inside app_name/templatetags .. Then open terminal in project folder give command python manage.py shell
from app_name.templatetags import my_templatetag
you just cut/remove your code which written inside the (example templatetags/home.py)
from home.py you remove your code and restart your server and again paste your code in home.py it will work.
The templatetags folder must have a __init__.py file in order to be a regular python package
Ensure that you also created the templatetags.py file next to the __init__.py file
For me, I had to register my customer Filter as this since my templatetags are outside of any app
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR, 'templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.media',
],
# ! New Line
'libraries':{
'customFilter': 'templatetags.customFilter',
}
},
},
]
at first stop the server.remove/cut the code from templatetags/tag.py and rewrite/paste it.then run the server.it worked for me
Yah, This problem you are currently facing because of older django version Or Complexly to write "Depreciation"
if You HAve These Types OF TAgs In Your template/ Html Files Change Them With..
> {{% load staticfiles %} or {% load admin_static %}, {% load
> admin_static %}}
change with
{% load static %}
Get to The Point..
JUst SImply Perform These Replace All These from YOur BAse.html/or Any type Of HTML

Cannot use overextends in Wagtail admin

I try to replace default logo and title in a Wagtail app. According to http://docs.wagtail.io/en/v1.0b1/howto/custom_branding.html I've created templates/wagtailadmin/, have installed django-overextends and added overextends to my project’s INSTALLED_APPS object(base.py).
As a result is error Invalid block tag on line 1: 'overextends'. Did you forget to register or load this tag?
How can I correctly load overextends module to make it work? Any help appreciated. Thanks in advance.
See the overextends readme
In Django 1.9+, you must add overextends to the builtins key of your TEMPLATES setting
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'builtins': ['overextends.templatetags.overextends_tags'],
}
},
]
For most extensions which feature template tags, you need to load them in each template, e.g. {% load overextends_tags %}, but overextends is different, and in earlier versions of Django it self-adds to the builtins, see https://github.com/stephenmcd/django-overextends/blob/master/overextends/models.py
Note, Wagtail 1.0 is an old version, and the latest is 1.5.2. The Wagtail 1.5.2 Custom Branding documentation does detail the above template configuration step.
Update October 2016: Wagtail is now well past version 1.5. See #gasman's comment below for more.

TemplateNotFound after installing django-messages and django-postman

I get a TemplateNotFound after I installed django-postman and django-messages. I obviously installed them separately - first django-postman, and then django-messages. This is so simple and yet I've spent hours trying to resolve this.
I'm using Django 1.8, a fresh base install using pip. I then installed the two above packages. The TEMPLATES portion of my settings.py file is as follows:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates'),
#os.path.join(BASE_DIR, 'templates/django_messages'),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Within my INSTALLED_APPS tuple, I've also installed the above packages as well.
Here's my addition to urls.py:
url(r'^messages/', include('django_messages.urls')),
No other changes were made to the system and yet when I go to /messages I get the following error message:
TemplateDoesNotExist at /messages/inbox/
django_messages/inbox.html
Request Method: GET
Request URL: http://localhost:8000/messages/inbox/
Django Version: 1.8.3
Exception Type: TemplateDoesNotExist
Exception Value:
django_messages/inbox.html
Exception Location: /projects/.virtualenvs/blatter/lib/python2.7/site-packages/django/template/loader.py in render_to_string, line 138
Python Executable: /projects/.virtualenvs/blatter/bin/python
Python Version: 2.7.6
The issue is because it extends from the site's base.html. It is also mentioned in postman documentation :- https://django-postman.readthedocs.org/en/latest/quickstart.html#templates
The postman/base.html template extends a base.html site template, in which some blocks are expected:
title: in <html><head><title>, at least for a part of the entire title string
extrahead: in <html><head>, to put some <script> and <link> elements
content: in <html><body>, to put the page contents
postman_menu: in <html><body>, to put a navigation menu
A possible solution can be found here :- django-postman extends a base.html that does not exist
The problem was resolved for django-messages after reviewing a called template and changing the extends/inheritance parameter.
The file that was being called, inbox.html, inherited "django_messages/base.html" ... which worked fine. "base.html" then inherited from "base.html," so there appeared to be some circular logic here causing the error. This is by default and wasn't added by me. When I removed the extends/inheritance declaration from "base.html" so that it didn't inherit from itself, django-messages worked.
Perhaps Django 1.8 changed some logic w/templates? Either way, issue resolved.

Use custom directory for "templatetags"

some one know if its likely use custom directory for "templatetags" eje: "my-project/templatetags"
Normal
My-Project-Name
My-App
__init__.py
templatetags
__init__.py
Need Some Like This
My-Project-Name
templatetags
__init__.py
This is possible. Just add location of your templatetags.py or templatetags directory to Django settings.py into OPTIONS in TEMPLATES setting.
In my case I put my templatetags in the libs/ directory that is located in project root dir.
You have two options, builtins or libraries:
TEMPLATES = [{
...
'OPTIONS': {
...
'builtins': [
'libs.templatetags'
],
# or as #x-yuri pointed out, you can put them in `libraries`
'libraries': {
'my_tags': 'libs.templatetags',
},
}
}]
If you use builtins, it is available everywhere and you don't need to use {% load %} for that.
If you use libraries you need to use {% load my_tags %}.
This is not possible. The reason being, templatetags must reside inside a django app.
From the documentation of templatetags:
Custom template tags and filters must live inside a Django app. If
they relate to an existing app it makes sense to bundle them there;
otherwise, you should create a new app to hold them.
The app should contain a templatetags directory, at the same level as
models.py, views.py, etc. If this doesn’t already exist, create it -
don’t forget the __init__.py file to ensure the directory is treated
as a Python package. After adding this module, you will need to
restart your server before you can use the tags or filters in
templates.