TemplateDoesNotExist at /music/1/favourite/ music/details.html - python-3.x

I am new to Django and i am using it's version 2.0.7. I have already created template named as details.html but it's still not showing
The video tutorial which i am referring is https://www.youtube.com/watch?v=qgGIqRFvFFk&list=PL6gx4Cwl9DGBlmzzFcLgDhKTTfNLfX1IK&index=24
The error which I got is this
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/music/1/favourite/
Django Version: 2.0.7
Python Version: 3.6.6
Installed Applications:
['music.apps.MusicConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Template loader postmortem
Django tried loading these templates, in this order:
Using engine django:
* django.template.loaders.app_directories.Loader: C:\Users\Adesh\Desktop\website\music\templates\music\details.html (Source does not exist)
* django.template.loaders.app_directories.Loader: C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\templates\music\details.html (Source does not exist)
* django.template.loaders.app_directories.Loader: C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\templates\music\details.html (Source does not exist)
Traceback:
File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\datastructures.py" in __getitem__
77. list_ = super().__getitem__(key)
During handling of the above exception ('song'), another exception occurred:
File "C:\Users\Adesh\Desktop\website\music\views.py" in favourite
22. selected_song = album.song_set.get(pk=request.POST['song'])
File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\datastructures.py" in __getitem__
79. raise MultiValueDictKeyError(key)
During handling of the above exception ('song'), another exception occurred:
File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner
35. response = get_response(request)
File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Adesh\Desktop\website\music\views.py" in favourite
26. 'error_message':"You did not select a valid song",
File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\shortcuts.py" in render
36. content = loader.render_to_string(template_name, context, request, using=using)
File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\loader.py" in render_to_string
61. template = get_template(template_name, using=using)
File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\loader.py" in get_template
19. raise TemplateDoesNotExist(template_name, chain=chain)
Exception Type: TemplateDoesNotExist at /music/1/favourite/
Exception Value: music/details.html
My template is as follows named as details.html
<img src="{{ album.album_logo}}">
<h1>{{ album.album_title }}</h1>
<h2>{{ album.artist }}</h2>
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% endif %}
<form action="{% url 'music:favourite' album.id %}" method="post" >
{% csrf_token %}
{% for song in album.song_set.all %}
<input type="radio" id="song{{ forloop.counter }}" name="song"
value="{{ song.id }}">
<label for="song {{ forloop.counter }}">
{{ song.song_title }}
{% if song.is_favourite %}
<img src="random_image.png"/>
{% endif %}
</label><br>
{% endfor %}
<input tye="submit" value="Favourite">
</form>

Check your template folders in the settings, in this part of the error you can see Django can't find the template:
Using engine django:
* django.template.loaders.app_directories.Loader: C:\Users\Adesh\Desktop\website\music\templates\music\details.html (Source does not exist)
* django.template.loaders.app_directories.Loader: C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\templates\music\details.html (Source does not exist)
* django.template.loaders.app_directories.Loader: C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\templates\music\details.html (Source does not exist)
These are the directories that Django tried to find the template in. The directories that Django looks for are specified in the settings.py file of your project, either this variable: TEMPLATE_DIRS or TEMPLATES has the paths that Django looks for templates.
Either move the template to one of these folders or add the folder where you've saved the template to this variable.
Also see this part of the Django documentation about templates:
https://docs.djangoproject.com/en/2.0/topics/templates/#django.template.backends.base.Template.render

Try to add the path of your "Template" directory on settings.py file. You can check the code block below; I added full path of my template directory to 'DIRS' in TEMPLATES part and it solved my problem.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [r'C:\Users\Exper\PycharmProjects\Django\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

write form fieldsets in Python3.7

I have updated my project from Python 2.7 and Django 1.8 to Python 3.7 and Django 3.0
Where BetterModelForm and fieldsets are suuported in Python 2.7
My first question is that can i use fieldsets in Python 3.7 ? If yes how can i write them in forms.py and html template
Here i am providing the code for froms.py where i am using BetterModelForm and it is for Python 2.7
from form_utils.forms import BetterModelForm, BetterForm
class CampaignMainForm(BetterModelForm):
class Meta:
model = Campaign
exclude = ['campaign_create_send_id',
'list_id',
'name',
'subject',
'created_by',
'send_datetime',
'send_timezone',
'from_name',
'from_email',
'reply_to_email',
'preview_url',
'template',
'text_file',
'assets',
'is_published',
'is_canceled',
'template_version',
'campaign_version']
fieldsets = [
['group',{
'fields': ['group'],
'legend': "Recipients",
}],
['template',{
'fields': ['stored_template'],
'legend': "Template",
}],
['templatedata',{
'fields': ['stored_template_data', 'stored_template_data_validated'],
'legend': "Template Content",
}],
]
I have updated my project from Python 2.7 and Django 1.8 to Python 3.7 and Django 3.0
Where BetterModelForm and fieldsets are suuported in Python 2.7
My first question is that can i use fieldsets in Python 3.7 ? If yes how can i write them in forms.py and html template
Here i am providing the code for froms.py where i am using BetterModelForm and it is for Python 2.7
from form_utils.forms import BetterModelForm, BetterForm
class CampaignMainForm(BetterModelForm):
class Meta:
model = Campaign
exclude = ['campaign_create_send_id',
'list_id',
'name',
'subject',
'created_by',
'send_datetime',
'send_timezone',
'from_name',
'from_email',
'reply_to_email',
'preview_url',
'template',
'text_file',
'assets',
'is_published',
'is_canceled',
'template_version',
'campaign_version']
fieldsets = [
['group',{
'fields': ['group'],
'legend': "Recipients",
}],
['template',{
'fields': ['stored_template'],
'legend': "Template",
}],
['templatedata',{
'fields': ['stored_template_data', 'stored_template_data_validated'],
'legend': "Template Content",
}],
]
here is my html template for python 2.7
{% for fieldset in form.fieldsets %}
<fieldset{% if fieldset.name != "templatedata" %} class="accordion-group"{% endif %}>
{% if fieldset.name != "templatedata" %}
<legend><bull class="bull {% if fieldset.legend == "Recipients" %}{% if object.group != None %}label-color-0d0{% endif %}{% elif fieldset.legend == "Template" %}{% if object.stored_template != None %}label-color-0d0{% endif %}{% else %}label-color-0d0{% endif %}"></bull> {{ fieldset.legend }}
<small class="muted">{% if fieldset.legend == "Template" %}{% if object.stored_template != None %}{{ object.stored_template.name }}{% endif %}{% endif %}{% if fieldset.legend == "Recipients" %}{% if object.group != None %}{{ object.group }} ({{ email_valid_count }} emails){% endif %}{% endif %}</small>
</legend>
.....
.....
{% endfor %}
Now please help me how can i write in python 3.7 forms.py and same functionality of html template in python 3.7

Reverse for 'action' with arguments '('',)' not found

I have error that seemed to happen to some other people, still I didn't figure out what am I doing wrong, so asking you all for help. Can you please support me with my code? As soon as I try to use form element with action "{% url 'mtg:action' card.name %}" I receive error Reverse for 'action' with arguments '('',)' not found
EDIT: I'd like to add that card name is suppsed to be written by the user, so its not available as page is loaded.
Thanks in advance!
views.py:
def index(request):
context = {'cards': Card.objects.all()}
return render(request, 'mtg/index.html', context)
def lookup(request, card_name):
context = {'card_lookup': Card.objects.all()}
return render(request, 'mtg/index.html', context)
def action(request, card_name):
card = get_object_or_404(Card, pk=card_name)
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('mtg:tmpl', args=card_name))
urls.py:
app_name = 'mtg'
urlpatterns = [
path('', views.index, name="index"),
path('<str:card_name>/img', views.lookup, name='img'),
path('<str:card_name>/action', views.action, name='action'),
]
index.html:
<body>
<form class="wrap" action="{% url 'mtg:action' card.name %}" method="post">
<input class="searchTerm"/>
<button class="center" name="search">Search for synergy</button>
<button class="center" name="lookup">Lookup a card</button>
</form>
{% if lookup_card %}<div>{{ card_lookup }}</div>{% endif %}
</body>
EDIT: as requested adding also logs of error:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 3.1.3
Python Version: 3.7.8
Installed Applications:
['mtg.apps.MtgConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Template error:
In template C:\Users\Sajemiur\PycharmProjects\MtG_reader\mtg_django\mtg\templates\mtg\index.html, error at line 45
Reverse for 'action' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<card_name>[^/]+)/action$']
35 : .wrap{
36 : width: 30%;
37 : position: absolute;
38 : top: 30%;
39 : left: 50%;
40 : transform: translate(-50%, -50%);
41 : }
42 : </style>
43 : </head>
44 : <body>
45 : <form class="wrap" action=" {% url 'mtg:action' card.name %} " method="post">
46 : <input class="searchTerm"/>
47 : <button class="center" name="search">Search for synergy</button>
48 : <button class="center" name="lookup">Lookup a card</button>
49 : {% if card_lookup %}<img src="{{ card_lookup }}" width="80" height="200"/>{% endif %}
50 : </form>
51 : </body>
52 : </html>
Traceback (most recent call last):
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Sajemiur\PycharmProjects\MtG_reader\mtg_django\mtg\views.py", line 14, in index
return render(request, 'mtg/index.html', context)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\template\loader.py", line 62, in render_to_string
return template.render(context, request)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\template\backends\django.py", line 61, in render
return self.template.render(context)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\template\base.py", line 170, in render
return self._render(context)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\template\base.py", line 162, in _render
return self.nodelist.render(context)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\template\base.py", line 938, in render
bit = node.render_annotated(context)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\template\defaulttags.py", line 446, in render
url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\urls\base.py", line 87, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\urls\resolvers.py", line 685, in _reverse_with_prefix
raise NoReverseMatch(msg)
Exception Type: NoReverseMatch at /
Exception Value: Reverse for 'action' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<card_name>[^/]+)/action$']
you used {% if lookup_card %} but you passed in your view card_lookup
and if you want only name of card than get only name from Card object context = {'cards': Card.objects.values(name)}

Include tag in TWIG not work,Run is blank

I don't know it not work.Server environment:
Twig:3.0
PHP:7.X
nginx:1.15.11
{{ include 'Include/header.html' }}
Templates file:
|-index.html
|-content.html
|-Include
|- head.html
|- footer.html
index.php:
$loader = new Twig_Loader_Filesystem(ROOT_PATH.'/Templates');
$twig = new Twig_Environment($loader, [
'cache' => ROOT_PATH.'/Cache',
'auto_reload' => true,
'debug' => true
]);
echo $twig->render('index.html');
index.html:
{{ include 'Include/head.html' }}
<article>
body
<article>
{{ include 'Include/footer.html' }}
it doesn't work,Page is blank.
First, try comment out if in dev
'cache' => ROOT_PATH.'/Cache',
then got typo error
{{ include 'Include/foother.html' }}
to
{{ include 'Include/footer.html' }}
I suggest you try do not include any sub twig first and render simple 1 twig first. If success then just include and try again.

Error transferring django project from windows to linux

My project with py3 and django worked well in win10. But when I tried to make it work in linux, a 404 eror of static file appeared.
The error message is below.
[28/Sep/2017 09:32:57] "GET /static/home/cys/prj/.../cls_demo/static/c73f33679ff4328816dee4450044174e.jpg HTTP/1.1" 404 1955
** Settings.py **
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'collected_static')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
os.path.join(BASE_DIR, "clsapp", "static"),
]
STATICFILES_FINDERS = (
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder"
)
**Sample of how I call static files through my templates**
{% load staticfiles %}
<div class="img" style="background-image: url('{% static img_path %}')">
</div>
There is different code between win10 version and linux version. Why did this error appear? How to fix it...

Compiling Bootstrap 3 in a Symfony 2 project on Windows

I have been trying for some time now to compile Bootstrap 3 in a Symfony 2 project on Windows. But I can't get it to work. My primary objective is to compile my very own LESS file. I called it "styles.less". In there, I want to be able to use bootstrap mixins like "make-xs-column" for example. So I need to import bootstrap.less for that.
Here is what I did so far:
In my composer.json, I added the bootstrap bundle:
{
...
"require": {
...
"twitter/bootstrap": "v3.0.3"
},
....
}
Since I want to use Bootstrap 3, I cannot use the lessphp filter, so I use the less filter instead. For that, I had to install nodejs, and then less (by running the command "npm install less -g"). Finally, I modified my config.yml like so:
assetic:
debug: "%kernel.debug%"
use_controller: false
bundles: [ JoePersonalWebSiteBundle ]
filters:
cssrewrite: ~
less:
node: "C:\\dev\\nodejs\\lessc.cmd"
node_paths:
- "C:\\dev\\nodejs\\node_modules"
apply_to: "\.less$"
Now, in my layout.html.twig, I added the following:
{% stylesheets filter='less' '#JoePersonalWebSiteBundle/Resources/less/styles.less' %}
<link rel="stylesheet" type="text/css" href="{{ asset_url }}">
{% endstylesheets %}
And in my "styles.less" file, I import"bootstrap.less" like so:
#import '../../../../../../vendor/twitter/bootstrap/less/bootstrap.less';
But I always get an error. In fact, even if my "styles.less" file is completely empty, I always get an error like this one:
[exception] 500 | Internal Server Error | Assetic\Exception\FilterException
[message] An error occurred while running:
"C:\dev\nodejs\lessc.cmd" "C:\Users\joe\AppData\Local\Temp\assDE7E.tmp"
Error Output:
[31mParseError: missing opening `{`[39m[31m in [39mC:\Users\joe\AppData\Local\Temp\assDE7E.tmp[90m on line 17, column 1:[39m
[90m16 });[39m
17 [0m[0m
[1] Assetic\Exception\FilterException: An error occurred while running:
"C:\dev\nodejs\lessc.cmd" "C:\Users\joe\AppData\Local\Temp\assDE7E.tmp"
Error Output:
[31mParseError: missing opening `{`[39m[31m in [39mC:\Users\joe\AppData\Local\Temp\assDE7E.tmp[90m on line 17, column 1:[39m
[90m16 });[39m
17 [0m[0m
I tried to create my own recess filter to use that instead of less (based on the work by boteeka found here). But that didn't work either. The less files never compile. Even an empty one, or a simple one.
Could someone please point me in the right direction? Is it possible on Windows, to compile Bootstrap 3 in a Symfony 2 project? If so, can someone give me the exact steps I should follow?
I use lessphp in windows with Bootstrap v3.0.0. The original idea is from http://mossco.co.uk/symfony-2/symfony-2-and-bootstrap-3-assetic-config-and-base-html-template-file/
I have also added to the entries for the fonts, icons.
My composer.json
"require": {
"components/jquery": "dev-master",
"leafo/lessphp": "v0.4.0",
"twbs/bootstrap": "v3.0.0",
},
For the config.yml copy 'cssembed' and 'yuicompressor' to '%kernel.root_dir%/Resources'
/java/
My config.yml
# Assetic Configuration
assetic:
debug: %kernel.debug%
use_controller: false
bundles: [ ]
java: C:\Program Files\Java\jre7\bin\java.exe
filters:
cssrewrite: ~
cssembed:
jar: %kernel.root_dir%/Resources/java/cssembed-0.4.5.jar
yui_js:
jar: %kernel.root_dir%/Resources/java/yuicompressor-2.4.7.jar
lessphp:
file: %kernel.root_dir%/../vendor/leafo/lessphp/lessc.inc.php
apply_to: "\.less$"
assets:
jquery_js:
inputs:
- "%kernel.root_dir%/../components/jquery/jquery.min.js"
filters: [?yui_js]
bootstrap_js:
inputs:
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/transition.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/alert.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/modal.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/dropdown.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/scrollspy.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/tab.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/tooltip.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/popover.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/button.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/collapse.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/carousel.js"
- "%kernel.root_dir%/../vendor/twbs/bootstrap/js/affix.js"
filters: [?yui_js]
bootstrap_less:
inputs:
- "%kernel.root_dir%/../vendor/twbs/bootstrap/less/bootstrap.less"
filters: [lessphp, cssembed]
fonts_glyphicons_eot:
inputs:
- "%kernel.root_dir%/../vendor/twbs/bootstrap/fonts/glyphicons-halflings-regular.eot"
output: "fonts/glyphicons-halflings-regular.eot"
fonts_glyphicons_svg:
inputs:
- "%kernel.root_dir%/../vendor/twbs/bootstrap/fonts/glyphicons-halflings-regular.svg"
output: "fonts/glyphicons-halflings-regular.svg"
fonts_glyphicons_ttf:
inputs:
- "%kernel.root_dir%/../vendor/twbs/bootstrap/fonts/glyphicons-halflings-regular.ttf"
output: "fonts/glyphicons-halflings-regular.ttf"
fonts_glyphicons_woff:
inputs:
- "%kernel.root_dir%/../vendor/twbs/bootstrap/fonts/glyphicons-halflings-regular.woff"
output: "fonts/glyphicons-halflings-regular.woff"
And here my base.html.twig
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>{% block title %}Welcome!{% endblock %}</title>
{% block stylesheets %}
{% stylesheets '#bootstrap_less' combine=true %}
<link href="{{ asset_url }}" type="text/css" rel="stylesheet">
{% endstylesheets %}
{% endblock %}
<link rel="icon" type="image/x-icon" href="{{ asset('favicon.ico') }}" />
</head>
<body>
{% block body %}{% endblock %}
{% block javascripts %}
{% javascripts '#jquery_js' '#bootstrap_js' filter='?yui_js' combine=true %}
<script src="{{ asset_url }}"></script>
{% endjavascripts %}
{% endblock %}
</body>
</html>
Somehow cssembed unnecessary or does not function properly and can be removed with this solution!

Resources