I am trying to send data to a template but it doesn't get rendered. The html file loads but the field {{patient}} is blank and doesn't show 'abcde'.
Here is my code:
views.py
def exam_table(request):
context = {'patient': 'abcde'}
return render(request, 'examtable.html', context)
examtable.html
<div class="row d-flex align-items-center">
<div class="col-9">
<h3 class="f-w-300 d-flex align-items-center m-b-0">
<i class="feather icon-arrow-up text-c-green f-30 m-r-10"></i>$
<p>{{patient}}</p></h3>
</div>
urls.py
urlpatterns = [
# The home page
path('', views.index, name='home'),
path('insert_patient',views.insert_patient,name='insert_patient'),
path('nurse_patient',views.nurse_patient,name='nurse_patient'),
path('examtable',views.exam_table,name='examtable'),
# Matches any html file
re_path(r'^.*\.*', views.pages, name='pages'),
]
it should pass a dictionary value
def exam_table(request):
context = {'patient': 'abcde'}
return render(request, 'yourpage.html', {'context': context})
Related
I am creating a followers list to the sidebar.
How can I get author_id in my custom tag?
#register.inclusion_tag('list_followers.html', takes_context=True)
def show_followers(context, author_id):
request = context['request']
if request.user.is_authenticated:
followers = Profile.objects.filter(name=author_id)
return {'followers': followers}
_sidebar.html
Thanks...
I tried to get author_id from views.py to posts_tags.py
def author_info(request, author_id):
"""return following users"""
current_user = request.user.id
author = User.objects.get(id=author_id)
..............
or get author_id in _sidebar.html somehow
{% load posts_tags %}
...........
<div class="media">
<div class="p-3 border bg-light">
<div class="container">
{% show_followers author_id=here %}
</div>
</div>
</div>
but I couldn't...
In your author_info view, pass the author_id to the show_followers tag using the context dictionary:
from django.shortcuts import render
def author_info(request, author_id):
current_user = request.user.id
author = User.objects.get(id=author_id)
context = {
'author_id': author_id,
}
return render(request, 'your_template.html', context)
In case you decide to use class based view the views.py will look like:
from django.views import View
from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.models import User
class AuthorInfoView(LoginRequiredMixin, View):
login_url = '/login/'
def get(self, request, author_id):
current_user = request.user.id
author = User.objects.get(id=author_id)
context = {
'author_id': author_id,
}
return render(request, 'your_template.html', context)
In your template (_sidebar.html), pass the author_id to the show_followers tag:
{% load posts_tags %}
...........
<div class="media">
<div class="p-3 border bg-light">
<div class="container">
{% show_followers author_id=author_id %}
</div>
</div>
</div>
--PROBLEM--
I have created a basic calculator using Django.
The app takes some basic form inputs before executing some calculations and returning the outcomes to the user, however I want the user's inputs to remain visible in the form on submission.
At present the followin experience occurs.
User enters values into form and submits using 'Calculate' button.
Results are returned as expected but form and values are no longer present.
User can press 'Calculate' button to return to start of process and blank form.
--DESIRED OUTCOME--
--CODE--
forms.py
from django import forms
class InvestmentForm(forms.Form):
starting_amount = forms.FloatField()
number_of_years = forms.FloatField()
return_rate = forms.FloatField()
annual_additional_contribution = forms.FloatField()
views.py
from django.shortcuts import render
from django.views import View
from .forms import InvestmentForm
class Index(View):
def get(self, request):
form = InvestmentForm()
return render(request, 'loancalculator/index.html', {'form': form})
def post(self, request):
form = InvestmentForm(request.POST)
if form.is_valid():
total_result = form.cleaned_data['starting_amount']
total_interest = 0
yearly_results = {}
for i in range(1, int(form.cleaned_data['number_of_years'] +1)):
yearly_results[i] = {}
# CALCULATE THE INTEREST
interest = total_result * (form.cleaned_data['return_rate'] / 100)
total_result += interest
total_interest += interest
# ADDITIONAL CONTRIBUTION
total_result += form.cleaned_data['annual_additional_contribution']
# SET YEARLY RESULTS
yearly_results[i]['interest'] = round(total_interest, 2)
yearly_results[i]['total'] = round(total_result,2)
# CREATE CONTEXT
context = {
'total_result': round(total_result,2),
'yearly_results': yearly_results,
'number_of_years': int(form.cleaned_data['number_of_years'])
}
# RENDER THE TEMPLATE
return render(request, 'loancalculator/index.html', context)
else:
form = InvestmentForm()
return render(request, 'loancalculator/index.html', {'form':form})
index.html
{% extends 'loancalculator/base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="row justify-content-center">
<div class="col-4 border bg-light">
<div class="row t-5">
<div class="col-12 col-md-6 mx-md-auto">
<h1> Investment Calculator</h1>
<h5> Enter the details below to see your estimate</h5>
<form action="" method="POST">
{% csrf_token %}
{{ form|crispy }}
<button class="btn btn-primary" type="submit">Calculate</button>
</form>
<br>
</div>
</div>
</div>
<div class="col-4 border">
<div class="row t-5">
<div class="col-12 col-md-6 mx-md-auto">
<h1>Investment Results</h1>
<h3> After {{ number_of_years }} years, your investment is worth ${{ total_result }}</h3>
<div class="mt-5">
<table class="table">
<thead>
<tr>
<th scope="col">Year</th>
<th scope="col">Interest</th>
<th scope="col">Total</th>
</tr>
</thead>
<tbody>
{% for key, value in yearly_results.items %}
<tr>
<th scope="row">{{ key }}</th>
<td>{{ value.interest }}</td>
<td>{{ value.total }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock content %}
Two ways you can go about doing what you want as I see it:
Method 1
Use sessions to hold the data and then refeed it to the form using initial form values. This is probably the easiest since it most closely matches what you already have.
class Index(View):
def get(self, request):
# Fill in the initial values on the unbound form:
initial = {
'starting_amount': request.session.get('starting_amount'),
'number_of_years': request.session.get('number_of_years'),
'return_rate': request.session.get('return_rate'),
'annual_additional_contribution': request.session.get('annual_additional_contribution'),
}
form = InvestmentForm(initial=initial)
return render(request, 'home/index.html', {'form': form})
def post(self, request):
form = InvestmentForm(request.POST)
if form.is_valid():
# After getting the cleaned_data, set a session variable to hold it
total_result = form.cleaned_data['starting_amount']
request.session['starting_amount'] = total_result
number_of_years = int(form.cleaned_data['number_of_years'])
request.session['number_of_years'] = number_of_years
return_rate = form.cleaned_data['return_rate']
request.session['return_rate'] = return_rate
annual_additional_contribution = form.cleaned_data['annual_additional_contribution']
request.session['annual_additional_contribution'] = annual_additional_contribution
total_interest = 0
yearly_results = {}
for i in range(1, number_of_years +1):
yearly_results[i] = {}
# CALCULATE THE INTEREST
interest = total_result * (return_rate / 100)
total_result += interest
total_interest += interest
# ADDITIONAL CONTRIBUTION
total_result += annual_additional_contribution
# SET YEARLY RESULTS
yearly_results[i]['interest'] = round(total_interest, 2)
yearly_results[i]['total'] = round(total_result,2)
# CREATE CONTEXT
context = {
# CHANGED: pass the 'form' to the context!
'form': form,
'total_result': round(total_result,2),
'yearly_results': yearly_results,
'number_of_years': number_of_years
}
# RENDER THE TEMPLATE
return render(request, 'home/index.html', context)
else:
form = InvestmentForm()
return render(request, 'home/index.html', {'form':form})
Method 2
From what you show here, anyway, you could just use JavaScript to do the calculations by grabbing the values directly from the DOM after they are entered, doing the calculations on the front end with JavaScript, and then fill in the values by targeting the locations where you want the results displayed in the DOM. No need for forms, no reloading of pages.
When you create the context, the value 'form' doesn't get set (views.py, under get())
A am working on a simple application, where trying to generate Dynamic URl and routing take place as per the ID in the url.
Dynamic value is getting populated in the URL, but it not performing action that needed.
prop_listings.html HTML Page:-
<div class="row text-secondary pb-2">
<div class="col-6">
<i class="fas fa-clock"></i> {{ listing.list_date | timesince }}
</div>
</div>
<hr>
More Info
</div>
</div>
</div>
URL.py in App Listings:-
from django.urls import path
from . import views
urlpatterns = [
path('',views.PropListings,name="prop_listings"),
path('<int:listing_id>', views.mlisting, name="morelisting"),
]
Views.py :-
def mlisting(request, listing_id):
# listingDetl = get_object_or_404(Listing, pk=listing_id)
listingDetl = Listing.objects.get(pk=listing_id)
print(listingDetl.username, listingDetl.address,listingDetl.city)
context = {
'listingDetails': listingDetl
}
return render(request,'listings/detail_listing.html', context)
URL.py in MainProject:-
urlpatterns = [
path('', include('static_pages.urls')),
path('user_account/', include('user_account.urls')),
path('listings/', include('listings.urls')),
path('feedback/', include('feedback.urls')),
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Am trying to redirect the page from prop_listings.html to detail_listing.html, based on the below tag URL generated on listing.id
More Info
It's not working as expected on-click of above tag.
But when i did inspect on the same, URL is getting generated properly and when i click on the url, it will work as expected.
Inspect on the html page, URL populated
I looked into similar issue threads and tried to make changes, but not able to fix it.
Not getting what the issue and how to correct it.
I'm trying to render an html file to pdf however while the pdf functionality is working fine the rendering is working properly, no css. Also it renders the whole page, how can i render specific sections of the html page. I'm using xhtml2pdf.
views.py file
from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template
from django.views import View
from xhtml2pdf import pisa
def render_to_pdf(template_src, context_dict={}):
template = get_template(template_src)
html = template.render(context_dict)
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return None
data = {
"company": "Name",
}
#Opens up page as PDF
class ViewPDF(View):
def get(self, request, *args, **kwargs):
pdf = render_to_pdf('listings/listing.html', data)
return HttpResponse(pdf, content_type='application/pdf')
urls.py file
path('pdf_view/', views.ViewPDF.as_view(), name="pdf_view"),
html file
<section class="p0">
<div class="container">
<div class="row listing_single_row">
<div class="col-sm-6 col-lg-7 col-xl-8">
<div class="single_property_title">
<span class="flaticon-photo-camera"></span> View Photos
</div>
</div>
<div class="col-sm-6 col-lg-5 col-xl-4">
<div class="single_property_social_share">
<div class="spss style2 mt10 text-right tal-400">
<ul class="mb0">
<li class="list-inline-item"><span class="flaticon-transfer-1"></span></li>
<li class="list-inline-item"><span class="flaticon-heart"></span></li>
<li class="list-inline-item"><span class="flaticon-share"></span></li>
<li class="list-inline-item"><span class="flaticon-printer"></span></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</section>
Thank you!
Ans 1.) If you want to style your html than directly use style property in tag. If you make class and use template inheritance than it is not going to work as it is independent html. Use style directly in html.
Ans 2.) if you want specific section of html in pdf than write content which you need in html or use style = “display: none ;” on section which you dont want in pdf.
The form field (text area) is not showing in my django template. I can figure out where the problem is.
Views.py
class Profile(View):
"""User Profile page reachable from /user/<username> URL"""
def get(self, request, username):
params = dict()
user = User.objects.get(username=username)
tweets = Tweet.objects.filter(user=user)
params["tweets"] = tweets
params["user"] = user
return render(request, 'profile.html', params)
class PostTweet(View):
"""Tweet Post form available on page /user/<username> URL"""
def post(self, request, username):
if request.method == 'GET':
form = TweettForm()
else:
form = TweetForm(self.request.POST)
if form.is_valid():
user = User.objects.get(username=username)
tweet = Tweet(text=form.cleaned_data['text'], user=user, country=form.cleaned_data['country'])
tweet.save()
words = form.cleaned_data['text'].split(" ")
for word in words:
if word[0] == "#":
hashtag, created = HashTag.objects.get_or_create(name=word[1:])
hashtag.tweet.add(tweet)
return HttpResponseRedirect('/user/'+username)
return render(request, 'profile.html', {'form': form})
forms.py
from django import forms
class TweetForm(forms.Form):
text = forms.CharField(widget=forms.Textarea(attrs={'rows': 1, 'cols':85}), max_length=160)
country = forms.CharField(widget=forms.HiddenInput())
profile.html
{% extends "base.html" %}
{% block content %}
<div class="row clearfix">
<div class="col-md-12 column">
<form method="post" action="post/">{% csrf_token %}
<div class="col-md-8 col-md-offset-2 fieldWrapper">
{{ form.text.errors }}
{{ form.text }}
</div>
{{ form.country.as_hidden }}
<div>
<input type="submit" value="post">
</div>
</form>
</div>
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from tweets.views import Index, Profile, PostTweet
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', Index.as_view()),
url(r'^user/(\w+)/$', Profile.as_view()),
url(r'^admin/', include(admin.site.urls)),
url(r'^user/(\w+)/post/$', PostTweet.as_view())
)
Only the submit (post) button shows on the on when rendered in the browser. The text are is not there
You get nothing since you are not passing the form to the template. Write get function in PostTweet view and include form = TweetForm() in it as a param passed to the template.