So my problem is i can access json data from server but i dont know how to display them properly, until now i can only display all model and i would like to display only some data.
My template
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
{% verbatim %}
<body ng-app="MyApp">
<div ng-controller="MyPerson">
<div ng-repeat="person in person">
<p>{{person}}</p>
<p>{{persons.city}}</p>
<p>{{person.city}}</p>
<p>{{person.id}}</p>
<script>
var MyApp = angular.module('MyApp', []);
MyApp.controller('MyPerson', function($scope, $http) {
$http.get('http://127.0.0.1:8000/people/person/?format=json').
success(function(personData) {
$scope.person = personData;
});
});
</script>
</div>
</div>
{% endverbatim %}
</body>
</html>
My urls
from django.conf.urls import patterns, include, url
from people.views import *
from django.contrib import admin
from people.api import PersonResource
from tastypie.api import Api
from django.contrib.auth.decorators import login_required
person_resource = PersonResource()
urlpatterns = patterns('',
url(r'^$', IndexView.as_view(), name='home'),
url(r'^first/$', FirstView.as_view(), name='first'),
url(r'^admin/', include(admin.site.urls)),
url(r'^people/', include(person_resource.urls)),
)
My api
from people.models import Person
from tastypie.resources import ModelResource
class PersonResource(ModelResource):
"""
API Facet
"""
class Meta:
queryset = Person.objects.all()
resource_name = 'person'
My model
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=255)
city = models.CharField(max_length=255)
slug = models.SlugField(unique=True)
parent = models.ForeignKey('Person', blank=True, null=True)
def __unicode__(self):
return "%s" % self.name
on terminal i get
[10/Dec/2014 18:38:20] "GET / HTTP/1.1" 200 797
[10/Dec/2014 18:38:20] "GET /people/person/?format=json HTTP/1.1" 200 420
and my html is
{"limit":20,"next":null,"offset":0,"previous":null,"total_count":3}
[{"city":"Budapest","id":1,"name":"Igor","resource_uri":"/people/job/person/1/","slug":"person"},{"city":"Warszawa","id":2,"name":"Karol","resource_uri":"/people/job/person/2/","slug":"person1"},{"city":"Jerozolima","id":3,"name":"Michal","resource_uri":"/people/job/person/3/","slug":"Ima"}]
So i can access json but it works only when i make ng-repeat person in persons
but then it only display data in these {{person}}
if i add sth else for example {{person.name}} it display nothing. I would like to display everything in nice format. I work on django and use rest Tastypie
If your JSON from http://127.0.0.1:8000/people/person/?format=json is coming back as an array then you need to change your $scope.person to be $scope.persons and your ng-repeat needs to read person in persons.
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.
I am a beginner to Django and unable to populate the items from my database table to <option></option>.
From models.py:
from django.db import models
from django.db.models.fields.related import ForeignKey
# Create your models here.
class Tbl_Category(models.Model):
cat_Id = models.AutoField(primary_key=True)
cat_Name = models.CharField(max_length=20, unique=True)
# def __str__(self):
# return [self.cat_Id, self.cat_Name]
class Tbl_Item(models.Model):
item_Id = models.AutoField(primary_key=True)
item_Name = models.CharField(max_length=30, unique=True)
cat_Idf = models.ForeignKey(Tbl_Category,on_delete=models.CASCADE)
item_Price = models.IntegerField()
From views.py:
from django.shortcuts import render
from orderapp.models import Tbl_Item
# Create your views here.
def displayMain(request):
return render(request,'index.html')
def ct(request):
options = Tbl_Item.objects.filter(cat_Idf=1)
context = {'alloptions' : options}
return render(request, 'index.html', context)
From index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{% load static %}
<link rel="stylesheet" href="{% static 'css.css' %}">
<title>DATA COLLECTION</title>
</head>
<body>
<div class="container">
<div class="order-screen">
<div class="element">
<label for="coffee-tea">Coffee-Tea</label>
<select name="coffee-tea" id="coffee-tea">
{% for opt in alloptions %}
<option value="{{opt.item_Id}}">{{opt.item_Name}}</option>
{% endfor %}
</select>
</div>
<div class="cart-screen">CART-SCREEN</div>
</div>
</body>
</html>
I assure you that my database connection is working absolutely fine and there was no problem while running makemigrations and migrate commands. My tables contain values that I have hardcoded. Please guide me with what is wrong with my approach. Thank you.
If I understand you question correctly you want to have a dropdown for different options in a form. In Django this would be done on the model with choices
example
OWNERSHIP=[
('current owner', 'Current Owner'),
('past owner','Past Owner'),
]
class Post(models.Model):
title = models.CharField(max_length=100)
ownership = models.CharField(max_length=100, choices=OWNERSHIP)
then just render the form field as {{ form.ownership }} and it will give you a dropdown
I am new to FastAPI and I need to understand if there is a way to download a dataframe in excel format at user selected location in their system. Below is the sample code I wrote but for downloading the dataframe as excel, I had to hardcode the system location in the code.
main.py code :
from fastapi import FastAPI, Request, Form
from pydantic import BaseModel
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
import uvicorn
import pandas as pd
app = FastAPI()
templates = Jinja2Templates(directory="htmlDirectory")
class NameValues(BaseModel):
Name : str = None
def save_to_excel(content, filename):
file = content.to_excel(r"E:\PycharmProjects"+"\\"+filename+".xlsx", index=False)
return file
#app.get("/home", response_class = HTMLResponse)
def home(request:Request):
return templates.TemplateResponse("introduction.html", {"request": request})
#app.post("/displayDF")
async def handle_df(request: Request, Name: str = Form(...), action: str = Form(...)):
if action == "Submit":
test_list = [["Joe", 34, "Accounts", 10000], ["Jack", 34, "Chemistry", 20000]]
data = pd.DataFrame(data=test_list, columns=["Name", "Age", "Dept.", "Salary"])
return templates.TemplateResponse(
'df_representation.html',
{'request': request, 'data': data.to_html()}
)
if action == "Download":
test_list = [["Joe", 34, "Accounts", 10000], ["Jack", 34, "Chemistry", 20000]]
data = pd.DataFrame(data=test_list, columns=["Name", "Age", "Dept.", "Salary"])
save_to_excel(data, Name)
return "File Downloaded successfully"
if __name__ == '__main__':
uvicorn.run('main:app', host='0.0.0.0', port=8000)
df_representation.html code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>displayDF</title>
</head>
<body>
<h2>DataFrame representation:</h2>
<!-- You've to mark your data as safe,
otherwise it'll be rendered as a string -->
{{ data|safe }}
<form action="/displayDF" method="post">
<input type="text" name="Name">
<input type="submit" name="action" value="Download">
</form>
</body>
</html>
introduction.html code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>
<h2>Please enter a string in the space provided</h2>
<form action="/displayDF" method="post">
<input type="text" name="Name">
<input type="submit" name="action" value="Submit">
</form>
</body>
</html>
The above code works fine but the only problem is that I have hardcoded location in save_to_excel method in main.py file. I need to change the code in such a way that user could select the desired location in their system and let program know where they want the dataframe downloaded in excel format. Thanks in advance for all the help!!
I am creating a news app using django. It consists of search by date option. When i choose the date(ex:29-11-2020) and click submit, It should take me to the news of that particular day. When i try the below code instead of showing the details it is giving me a blank page.
views.py
from django.shortcuts import render
from .models import *
from django.views.generic.detail import DetailView
from django.views.generic import ListView
def index(request):
return render(request,'newspaperapp/index.html')
class nowlist(ListView):
model = newsmodel_1
template_name = 'newspaperapp/index.html'
class newslist(DetailView):
model = newsmodel_1
template_name = 'newspaperapp/home.html'
context_object_name = 'newspaperapp'
# search by giving date in index and search date
class SearchView(ListView):
model = newsmodel_1
template_name = 'newspaperapp/search.html'
context_object_name = 'all_search_results'
def get_queryset(self):
result = super(SearchView, self).get_queryset()
query = self.request.GET.get('search')
if query:
postresult = newsmodel_1.objects.filter(date_published__contains=query)
result = postresult
else:
result = None
return result
urls.py
from django.urls import path
app_name = 'newspaperapp'
from .views import newslist,SearchView,nowlist
from newspaperapp import views
urlpatterns = [
path('',views.index,name='index'),
path('date/',nowlist.as_view(),name = "date"),
path('<int:pk>',newslist.as_view(),name = "home"),
path('results/', SearchView.as_view(), name='search'),
]
newspaperapp/home.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p>Today's Paper</p>
{{newspaperapp.date_published}}
{{newspaperapp.category}}
</body>
newspaperapp/index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<!-- this page has search option and different categories of news -->
<!-- to create search option we write views code and continue -->
<form class="form-inline my-2 my-lg-0" method="GET" action="{% url 'newspaperapp:search' %}">
<input class="form-control mr-sm-2" type="date" placeholder="Search" aria-label="Search"
name="search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
{%for newspaperapp in object_list %}
<li>{{newspaperapp.title}}
{{newspaperapp.date_published}}
{%endfor%}
</ul>
</body>
</html>
newspaperapp/search.html
{% block content %}
{% for newspaperapp in all_search_results %}
<h3></h3>
{% empty %}
<h2>No results found</h2>
{% endfor %}
{% endblock %}
Contain usually translated to LIKE in sql typically is used to search for a specified text pattern in a column.
If you want to filter date, you could convert query it to datetime object, and search the objects in that particular date range using gte and lt lookups.
from datetime import datetime, timedelta
class SearchView(ListView):
model = newsmodel_1
template_name = 'newspaperapp/search.html'
context_object_name = 'all_search_results'
def get_queryset(self):
result = super(SearchView, self).get_queryset()
query = self.request.GET.get('search')
# query is of type 'str', convert to datetime
start_day = datetime.fromisoformat(query)
end_day = start_day + timedelta(days=1)
if query:
postresult = newsmodel_1.objects.filter(
date_published__gte=start_day,
date_published__lt=end_day
)
result = postresult
else:
result = None
return result
Note: add more logic to handle query is None
I'm trying to add functionality to my Django site to upload files to an AWS S3 bucket. I found django-s3direct, which seems perfectly suited. After following all the setup instructions, though, I'm getting an error rendering the very basic HTML template:
<html>
<head>
<meta charset="utf-8">
<title>s3direct</title>
{{ form.media }}
</head>
<body>
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
</form>
</body>
</html>
I get the error Reverse for 's3direct' not found. 's3direct' is not a valid view function or pattern name. on the line with {{ form.as_p }}.
In my urls.py I have (as specified in the s3direct docs):
from django.conf.urls import url
from .views import get_upload_params, generate_aws_v4_signature, MyView
app_name = 's3direct'
urlpatterns = [
url(r'^$', MyView.as_view(), name='form'),
url('^get_upload_params/', get_upload_params, name='s3direct'),
url('^get_aws_v4_signature/', generate_aws_v4_signature, name='s3direct-signing'),
]
In forms.py:
from django import forms
from s3direct.widgets import S3DirectWidget
class S3DirectUploadForm(forms.Form):
csv = forms.URLField(widget=S3DirectWidget(dest='csv_destination'))
And in views.py (along with a couple other long functions from s3direct):
from django.views.generic import FormView
from .forms import S3DirectUploadForm
class MyView(FormView):
template_name = 'form.html'
form_class = S3DirectUploadForm
I've configured an IAM policy and added keys to my Django settings file, as well as made a CORS policy for my S3 bucket. I'm using Django 2.0. I'm stuck on this reverse error, and can't seem to figure out what's causing it.
According to docs urls.py should contain
urlpatterns = [
url(r'^s3direct/', include('s3direct.urls')),
]