I am unable to fetch data to html page from database in django - django-models

I am trying to fetch data to html page from database but i am not getting any output on the html page
models.py
from django.db import models
class image(models.Model):
name=models.CharField(max_length=100)
img=models.ImageField(upload_to='slideshow1')
admin.py
from django.contrib import admin
from .models import image
# Register your models here.
admin.site.register(image)
views.py
from django.shortcuts import render,redirect
from django.http import HttpResponse
from django.contrib.auth.models import User,auth
from django.contrib import messages
from .models import image
def slideshow1(request):
dest=image.objects.all()
return render(request,'slideshow1.html',{'dest':dest})
urls.py
from django.urls import path,include
from . import views
urlpatterns = [
path('login/',views.login,name='login'),
path('signup/',views.signupform,name='signup'),
path('logout/',views.logout,name='logout'),
path('slideshow1',views.slideshow1,name='slideshow1'),
]
slideshow1.html
{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
{% block content %}
<h1 >{{image.name}}</h1>
{% endblock %}
</body>
</html>

you can not access all the data without using 'for loop' even you have only one entry in the table. So use loop to extract it.
{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
{% for x in image %}
<h1 >{{x.name}}</h1>
<img src="{{x.img.url}}">
{% endfor %}
</body>
</html>

Related

django multiple checkbox values show a template?

from django import forms
class MyForm(forms.Form):
checkbox = forms.MultipleChoiceField(
choices=[('apple', 'apple'), ('orange', 'orange')],
widget=forms.CheckboxSelectMultiple
)
urls
from django.urls import path
from . import views
urlpatterns=[
path('myform/',views.my_form,name='my_form')
]
views
from django.shortcuts import render
from aapp.forms import MyForm
# Create your views here.
def my_form(request):
if request.method == 'POST':
selected = request.POST.getlist('checkbox')
print(selected)
else:
form = MyForm()
return render(request, 'my_form.html', {'form': form})
urls
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('aapp.urls'))
]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button id="submit-btn" type="submit">Submit</button>
</form>
</body>
<
when i click checkbox apple - i need to show apple? How to fix it?
Any other ways to print checkbox values in a template in Django-models-forms-templates?
Multiple checkbox value shows on templates when i click the value

React component render in Django Template

I have a Django view through which I want to render a React component. But unable to do so. This is my Django template.
{% extends "base.html" %}
{% block javascript %}
<script>
window.props = {{props}}; // make sure to escape your props to prevent XSS! See here for the source for the json filter: https://gist.github.com/pirate/c18bfe4fd96008ffa0aef25001a2e88f
window.react_mount = document.getElementById('react');
</script>
<!-- Load React. -->
<!-- Note: when deploying, replace "development.js" with "production.min.js". -->
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js" crossorigin></script>
<script src="/static/components/{{component}}" type="text/babel"></script>
{% endblock javascript %}
{% block content %}
<div class="container">
<div class="card">
<div class="card-body">
<div id="react">
<!-- Contents get replaced by mounted React.Component -->
<i class="fa fa-lg fa-spinner fa-spin"></i><br><br>
<i class="pending">Loading components...</i><br><br>
</div>
</div>
</div>
</div>
{% endblock content%}
This is my React component.
import React from 'react'
import ReactDOM from 'react-dom'
class HelloWorld extends React.Component {
render() {
return <h1>Hello World!</h1>;
}
}
ReactDOM.render(
React.createElement(HelloWorld, window.props), // gets the props that are passed in the template
window.react_mount, // a reference to the #react div that we render to
)
I am getting following error:
Uncaught ReferenceError: require is not defined
I followed this solution and it works. The problem was that I need to configure webpack (see webpack.config.js file) which bundles the JS files.

add code blocks to end of body and inside head from template in CakePHP

I have used Django and in Django template engine we define blocks like
<head>
{% block head %} {% endblock head %}
</head>
<body>
{% block content %} {% endblock content %}
.....
{% block script %} {% endblock script %}
</body>
</html>
in each template file extending this layout we include codes in particular blocks to put in head, body, script respectively.
Now, I'm using CakePHP and want to achieve the same as I have lot of js files at the end of body tag and include script below them which are particularly for each page. Means, that script will be called from particular page only and thus I can't put it on all pages.
The layout of CakePHP looks like
<html>
<head>
<!-- all head elements -->
</head>
<body>
<?= $this->fetch('content') ?>
<!-- all js includes -->
</body>
</html>
How to add script at the end of body tag in CakePHP 3?
It's all explained in the manual here
In your view file
<?php
$this->Html->script('yourjavascriptfile', ['block' => 'scriptBottom']);
?>
then in your layout
<body>
<?= $this->fetch('content') ?>
<?= $this->fetch('scriptBottom') ?>
</body>

Serving HTML+CSS+JS(angular) with flask

What i want to do is, just send down the HTML+css+js files as static pages on some routes like:
#app.route('/', methods=[GET])
def index():
return <html+css+js>
Particularly i would like to stay away from templates, and rely on ajax/websocket connecting to other routes of the flask app to get the JSON objects and update the webpage. Also I had a hard time in linking css and js files in html. The url_for method seems to completely rely on template system and doesn't seem to work properly in my case.
eg.
Directory Structure
redirect-server(app home folder)
static
index.html
main.js
venv(python3 virtualenv)
main.py(flask app)
main.py
from flask import Flask, redirect
from flask import render_template
app = Flask(__name__)
#app.route('/')
def index():
return redirect("/abc/xyz")
#app.route('/abc/xyz')
def abc():
return app.send_static_file("index.html")
app.run(debug=True)
index.html
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
<script type="text/javascript" src="{{ url_for('static', filename='main.js') }}"></script>
</head>
<body>
<h1>Welcome!</h1>
</body>
</html>
The error I get is the following
127.0.0.1 - - [28/Oct/2015 14:07:02] "GET /abc/%7B%7B%20url_for('static',%20filename='main.js')%20%7D%7D HTTP/1.1" 404 -
The HTML is returned fine but it cannot find the js file
You send the template as a static file.
app.send_static_file("index.html")
Better render it, as shown in the docs :)
there is no way i could find this to work without relying on templates.
The following worked for me
restructuring my directories as follows
redirect-server
static
main.js
templates
index.html
main.py
main.py
from flask import Flask, redirect
from flask import render_template
app = Flask(__name__)
#app.route('/')
def index():
return redirect("/abc/xyz")
#app.route('/abc/xyz')
def abc():
return render_template("index.html")
app.run(debug=True)
index.html
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
<script type="text/javascript" src="{{ url_for('static', filename='main.js') }}"></script>
</head>
<body>
<h1>Welcome!</h1>
</body>
</html>

Including javascript files with templates

I am using AppEngine with the webapp framework (python). In my script I am generating javascript code dynamically with Django, for example:
python controller file
template_values = {
'page': '1',
}
path = os.path.join(os.path.dirname(__file__), "../views/index.html")
self.response.out.write(template.render(path, template_values))
index.html file
<html>
<head>
...
<script>
{% if page %}
alert("test");
{% endif %}
</script>
</head>
<body>
...
</body>
</html>
Now, instead of using inline <script> tags I would like to use the <link> tags with a reference to a JS file containing the script. However, I can't quite understand I can do that using the templates engine. If I include a JS file (dynamically) it would somehow have to know the value of "page", but "page" is known in the scope of index.html only.
Any ideas?
Thanks,
Joel
If you want dynamically generate your javascript code in your html,
you can write the code inside python code
page = 0
template_values = {
'js_code': 'alert("test:'+str(page)+'")',
}
path = os.path.join(os.path.dirname(__file__), "../views/index.html")
self.response.out.write(template.render(path, template_values))
in index.html
<script>
{{js_code}}
</script>
If you want to generate a js file dynamically, you can try to pretend there is a js file,
and generate its content.
class JSHandler(BaseHandler):
def get(self):
page= str(self.request.get("page"))
js_code ='alert("page:'+page+'");'
self.response.out.write(js_code)
def main():
application = webapp.WSGIApplication([
('/code.js', JSHandler),
], debug=True)
wsgiref.handlers.CGIHandler().run(application)
Then you can write this code in your html
<script type="text/javascript" src="/code.js?page={{page}}">></script>
You are either over-complicating a simple situation, or you haven't explained your problem clearly.
If you want to include an externally-located JavaScript file, you would use a <script> tag, not <link>.
If you have template code like this:
<html>
<head>
{% if page %}
<script type="text/javascript" src="/js/foo.js"></script>
{% endif %}
</head>
...
</html>
and page is not None, the template will render the following HTML to the browser:
<html>
<head>
<script type="text/javascript" src="/js/foo.js"></script>
</head>
...
</html>
and the browser will try to load the resource pointed to by the <script> tag. The browser has no knowledge of how that tag got into the HTML that it loaded.

Resources