I need to get the param of the url inside a html file, but I need to know if is possible in a tag, or how can I get the url params using Class-based views?
My urls.py file
from django.urls import path
from .views import UsersView
urlpatterns = [
path('list/<int:pk>/', UsersView.as_view(), name='user_list'),
]
My html file:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Users</title>
</head>
<body>
{{ request.GET.pk }}
</body>
</html>
You can use
self.kwargs['pk']
Inside a CBV to get the URL parameter, since there is a <int:pk>
Related
My template is as follows:
<!-- template1.html -->
<html>
<head>
<title>Item Details</title>
</head>
<body>
<p>{{ req }}</p>
</body>
</html>
To render the template I am using the following code:
from fastapi import FastAPI
from fastapi.templating import Jinja2Templates
app = FastAPI()
template = Jinja2Templates(directory="templates")
#app.get("/list_items")
def home(request: Request):
return template.TemplateResponse('template1.html',{"req": req})
#app.get("/", response_class=HTMLResponse)
async def read_items():
return """
<html>
<head>
<title></title>
</head>
<body>
<form action="/list_items">
<input type="text" placeholder="Search.." name="search">
<button type="submit">Search</button>
</form>
</body>
</html>
"""
But I do not want to use a separate folder with files for a simple template. How do I pass the html text instead of the function TemplateResponse
You can use HTMLResponse. Pass HTMLResponse as the parameter response_class of your route.
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
app = FastAPI()
#app.get("/items", response_class=HTMLResponse)
def read_items():
return """
<html>
<head>
<title>Some HTML in here</title>
</head>
<body>
<h1>Look ma! HTML!</h1>
</body>
</html>
"""
You can also override the response directly in your endpoint, by returning it.
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
app = FastAPI()
#app.get("/items")
def read_items():
html_content = """
<html>
<head>
<title>Some HTML in here</title>
</head>
<body>
<h1>Look ma! HTML!</h1>
</body>
</html>
"""
return HTMLResponse(content=html_content, status_code=200)
Update
Jinja2Templates.TemplateResponse expects as name parameter a filename that is pointing to the template your would like to return, and which lies in the Jinja2Templates directory you defined (e.g., Jinja2Templates(directory="templates") ). You can't pass the template contents to its place. Jinja2Templates will attempt to retrieve the file you passed using the directory you defined earlier, see here -> here -> here. Hence, what you are asking, it doesn't seem to be natively possible (but, with some hackish stuff maybe doable); however, there is nothing wrong with having a templates directory, even for small template files.
UPDATE: This solved. I didn't write the correct CSS!
I am trying to render a few things in HTML. Multiple things are causing problems but I've included the most basic part I want to get working. If I can get this to work, I can get the rest to work.
Very simple app structure:
app
api.py
static
styles.css
templates
index.html
This is the contents of index.html:
<html>
<h1>
Title here
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="{{ url_for('static', path='/styles.css') }}" rel="stylesheet">
</h1>
</html>
This the the CSS I'm using:
h1 {
color: red
text-align: center
}
Relevant code in api.py:
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
app = FastAPI()
templates = Jinja2Templates(directory="templates")
app.mount("/static", StaticFiles(directory="static"), name="static")
#app.get("/", response_class=HTMLResponse)
def read_mean_cpu(request: Request, device_id):
return templates.TemplateResponse("index.html", {"request": request}))
Any idea why the CSS isn't taking?
I am trying to make a webpage using flask and html with
render_template()
but I cant see any text from my html document. I see the <title> appear, but nothing from the paragraphs is showing up.
Here is my code:
from flask import Flask, render_template
from threading import Thread
app = Flask('', template_folder='/home/runner/Alix')
#app.route('/')
def main():
return render_template('home.html')
def run():
app.run(host="0.0.0.0", port=8080)
def keep_alive():
server = Thread(target=run)
server.start()
I am using the keep_alive() function in a separate file, with a discord bot.
Here is my html:
<html>
<head>
<title>[ALIX FLASK SERVER]<title>
<style>
body{
background_color: black;
}
</style>
<head>
<body>
<p>
This text wont show
</p>
</body>
</html>
You have not closed the head tag, the second one should be </head>
i am following a tutorial based on django 2 and currently running version 3 of django, the problem i am facing is the identifying path of the tag on the front end of index.html, i'll post the code bellow , kindly tell me where i went wrong and any other mistakes
my settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS= (os.path.join(BASE_DIR, 'static'),) #static root added (A2)
MEDIA_ROOT=os.path.join(BASE_DIR, 'media')
MEDIA_URL='/media/'
my urls.py of main project
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('',include('posts.urls')),
path('user/',include('user.urls')),
path('admin/', admin.site.urls),
]+ static(settings.STATIC_URL, document_root=settings.MEDIA_ROOT)
my models.py of app
class Posts(models.Model): #created this model field
def min_len(val): #this is the custom validator working
if len(val)<=9:
raise validators.ValidationError("%(val)s Must be more than 10", params={'val':val})
title=models.CharField(validators=[min_len],max_length=255) #validation list provided
content=models.TextField(validators=[min_len])
thumb_nail=models.FileField(upload_to="posts/",null=True) #file field added
class Posts_Form(forms.ModelForm): #to build a form using django and not html
class Meta: #will get data of the fields=[] only
model=Posts
fields=['title','content','thumb_nail','user','category']
views.py
def index(request):
form=Posts_Form() #created form object
data=Posts.objects.all() #retrive data from the model to display
category=Category.objects.all() #we get all data of category
if request.method=='POST':
form=Posts_Form(request.POST,request.FILES) #request.FILES for file data
if form.is_valid():
# data=Posts(
# title=request.POST['title'],
# content=request.POST['content'],
# )
form.save()
return redirect('/')
return render(request,'index.html',{'title':'Add New Post','form':form,'rows':data,'categories':category})
and my index.html
{% extends "layout.html" %}
{% load static %}
{% block content%}
{%for row in rows%}
<h2>
{{row.title}}
</h2>
<p>
{{row.content}} - <small> {{row.created_at}}-{{row.user.username}} </small>
</p>
<p><img src="{%static 'row.thumb_nail.url' %}" alt="My image" width="150"> </p>
<p>{{row.category.all|join:", "}} </p>
{%endfor%}
</div>
and my layout.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width , initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>
{{title}}
</title>
<!--the below line is for the css bootstrap, from cdnjs official site-->
<!--link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css"-->
</head>
<body>
{% block content %} {% endblock %}
</body>
</html>
I have managed to render my component on a div on my template like so:
Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Example</title>
</head>
<body>
{% load render_bundle from webpack_loader %}<h1>Example</h1>
<div id="react-app"></div>
{% render_bundle 'main' %}
</body>
</html>
My react app:
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
const rootElement = document.getElementById('react-app');
ReactDOM.render(<App />, rootElement);
Whats a good approach to pass in data to react? i'm using Django templates
It is possible to pass props to the root element through data attributes and pass them to root element in index.js
<div
id="root"
data-custom-props='{aKey: "a value"}'
></div>
index.js file:
ReactDOM.render(<App {...(root.dataset)}/>, root);
A common pattern is to output a json string into a script tag, which you can then refer to in your init function.
For example:
// Above where you include your main bundle
<script>
window.__INITIAL_STATE.__ = { your: 'DATA', encodedIn: 'json', here: true }
</script>
You can then reference window.__INITIAL_STATE__ in your index.js and pass data as props into your root component.
What data do you want to pass to react?
Props is the concept that allow user to pass data from one component to another within react. It is not made to pass data from outside world to react app.
I believe this answer can guide you in right direction.
How to get Django and ReactJS to work together?
also read following to get some idea of back-end and front-end working together.
http://geezhawk.github.io/using-react-with-django-rest-framework
http://www.openmindedinnovations.com/blogs/3-ways-to-integrate-ruby-on-rails-react-flux