template.render() python subfunction in Django 1.11 not available - python

So, I have PyCharm 2017.2.3, and Python 3.6, and Django 1.11. while practicing on the test project, I tried to render to my index.html in view.py under my app. Below is the piece of code that I am talking about:
def index(request):
db_Conn = Album.objects.all()
template = loader.get_template('/music/index.html')
context = {
'db_Conn': db_Conn,
}
return HttpResponse(template.re)
Inside return HttpResponse, I can get until template, but when I use a period after template to use the render() sub-function, I do not get any suggestion from PyCharm for render() instead, I could see two other functions which not relevant to my post.
Can sombody help me on this. My learning is halted due to this.

Try this. I assume music is app name, so your template file should be in, music/templates/index.html
from django.shortcuts import render
from django.utils import timezone
def index(request):
return render(request, 'index.html', {'start_date':timezone.now()})
If not understood refer to this repo

Related

Passing values from python to html with django in views.py does not work

Hello I am following a django tutorial and the tutorial (FreeCodeCamp btw, they deserve to be noticed more) showed how to make a simple word counter in django. Now the thing is: While rendering the html file he passes some data to it like this:
def counter(request):
words = request.GET['text']
numberOfWords = len(words.split())
return render(request, 'counter.html', {'amount_of_words': int(numberOfWords)})
(I noticed that after publishing it seems like there is not the right spacing for functions, there actually is)
Screenshot of the source code
For the youtuber it works really fine, but for me it seems there is no way to display the data. in the html file i put this:
the number of words is {{amount_of_words}}
Which is exactly the same thing the tutorial guy did. Even if I add proper html boilerplate it doesn't seem to work
from unicodedata import name
from django.urls import path
from . import views
urlpatterns = [
path('', views.index , name='index'),
path('counter', views.counter, name="counter")
]
this is the urls.py file inside the app folder.
When loading counter it just shows "the message the number of words is " without display the value i pass from views.py
Even with a super simple example like this:
views.py:
def index(request):
person_name = {
'name': 'John',
}
return render(request, 'index.html', person_name)
index.html code:
<h1>ciao {{name}}</h1>
url when i load the page: http://127.0.0.1:8000/
I don't get why it would not work for me.
Your request http://127.0.0.1:8000/ is missing the path to your view as well as the GET parameter.
Try: http://127.0.0.1:8000/counter?text=Test
def counter(request):
words = request.GET['text']
numberOfWords = len(words.split())
amount_of_words = int(numberOfWords)
context = {
'amount_of_words': amount_of_words,
}
return render(request, 'counter.html', context)

Django url kwargs in templates

Previously we have been accessing kwargs in Django templates with {{view.kwargs.kwarh_name}}.
However, it has been to my surprise that this is not working in my django 3.2.4+
Has it been removed, is there any issue with the line above?
Note: Kwargs here I mean something like below:
Given a function as below:
def GetSomething(request, code):
return render(request, "some template here")
Now, the urlpatterns would be something like,
import GetSomething from .views
app_name = "some_app_name_here"
urlpattern = [
path("link/<int:code>/", GetSomething, name="some_cool_name") #http:localhost/link/12345/
]
Now in HTML/Django templates or Jinja2(whichever you use), accessing this code would be via {{ view.kwargs.code }}
But it so happens that this is not working for me in Django 3.2, any reasons??
Hope I was very clear!
The get_context_data method of class based views adds the view to the context as view. If you have a function based view, it will not be added to the context automatically. This is not related to Django versions 3.2.4+
So either use a class based view or use a function based view and pass the kwargs to the template through the context variable.
def GetSomething(request, code):
context = {
#some values here
'code':code,
}
return render(request, "some template here", context)
Then you can access your context variables in the template directly.
{{code}}

django template variable in <a>

How can i add a django template variable to href attribute of tag?something like this
{{meeting.meeting_url}}
meeting.url stores a link to another website such as google etc and it is saved in database
Thanks in advance
To render meeting.meeting_url in your template you need to pass the meeting object as argument of the render function in your view.
More about the render function here
Here's an example of what should be done:
from django.shortcuts import render
from .models import Meeting
def my_view(request):
# View code here...
context = {'meeting': Meeting.objects.first()} # first is an example, put whatever you want
return render(request, 'myapp/index.html', context)
You must make sure that your url (www.google.com) does start by a / because it would refer to the root url of your website (127.0.0.1:8000) which redirects you to 127.0.0.1:8000/meeting/meeting-info/www.google.com

Django Templates can not access to context

I checked all the questions and answers in this site, but could not find a solution. I am new in Django, trying to develop a storage model and stucked already in the ListView.
part of my view.py:
from django.shortcuts import render, redirect
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from Storage.models import Storage
from django.http import HttpResponse
class StorageListView(LoginRequiredMixin, ListView):
model = Storage
print(Storage.objects.order_by('-barcode'))
template_name = 'Storage/Storagelist.html'
def get_queryset(self):
return Storage.objects.order_by('-barcode')
I add print statement to check whether I reach the model and
everyting seems normal:
<QuerySet [<Storage: 123>, <Storage: 122>, <Storage: 121>]>
However, I can not reach the context from the template file 'Storagelist.html':
<h3>trial</h3>
{% if storage_list %} <h3>trial</h3> {% endif %}
Just to check access via url configurations, I added 'trial' at the beginning of the template and it also seems normal. I also tried to use context_object_name, but did not help either. Somehow, I can not reach to ListView context data from the template.
My versions of applications are as follows:
Django 2.0.3
Python 3.6.1
Can somebody please help me?
In a ListView I believe the objects will populate into the template as object_list. You might consider using this method to make the template context variable human readable (and also match what you are expecting). In other words, try adding context_object_name = storage_list to your view.

what's the alternative solution of tornado's "write" in django?

I am using django 1.4. I am moving codes from tornado to django. There is self.write() at the end of a class. What 's the alternative solution to self.write()? HttpResponse? There is only one template page
so Do I need to response to other page? can I just call response? or render_to_response to the template page again to wrape data to the page? Is write() same with HttpResponse()?
Hey, guys. there are many "?" above, But I only have one problem. An alternative solution of tornado's "write()" in django.
thx for ur time.
The code in tornado looks like:
class DataHandler(tornado.web.RequestHandler):
...
val = ...
self.write(val)
Maybe in django?
def DataHandler(request):
...
val = ...
return HttpResponse(val)
Is that clear about my question?
HttpResponse is typically used if you wish to return non-template responses.
To render templates, use render from django.shortcuts, for example:
from django.shortcuts import render
def some_handler(request):
context_for_template = {}
return render(request, 'template_name.html', context_for_template)
From Tornado's documentation, write seems to be able to automatically convert a dictionary to JSON. HttpResponse does not do that by default, you should look at Creating a JSON response using Django and Python if it is part of your use case.
the HttpResponse module
from django.http import HttpResponse
def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return HttpResponse(html)

Categories

Resources