Hi thank you for helping, I'm poor in coding.
To point: I'm doing a Django project that pass data form data-base to front-end; but right now i can't even pass anything views of Django into templates, I suspect i'm passing the wrong variable types; please do comment on your thought.
This is my code on views.py:
from django.shortcuts import render
def index (requset):
return render(requset,'myapp/index.html') # link to be able open frountend
def testdex(requset):
text = "hello world"
context ={'mytext' : text }
return render(requset,'myapp/inculdes.html', context)
so my variable will be pass into inculdes where extend to index page
This my codes on in inculdes.html:
{% exntends "myapp/index.html" %}
{% block includes %}
{{ mytext }}
{% endblock includes %}
this my code on index.html:
<body>
{% block includes %} {% endblock includes %}
</body>
Thanks again on giving me your time to help me and appreciate it if could write me some code because try fix this for whole week
You can try something like this:
views.py
from django.template.response import TemplateResponse
def testdex(request, template_name="myapp/includes.html"):
args = {}
text = "hello world"
args['mytext'] = text
return TemplateResponse(request, template_name, args)
includes.html
{% extends "myapp/index.html" %}
{% block includes %}
{{ mytext }}
{% endblock includes %}
And make sure you have set path for templates in settings.py
When you do {% block content %}{% endblock content %} you are telling Django that you want to be able to overwrite this section. Please note the word content can be anything to reflect what you want to overwrite.
When you do {{ variable }} you are telling Django that you want to pass a Context. In this example, variable I want to pass is called Title as the key and Portfolio as the value. Context is a dictionary that you pass in views.py like this:
def portfolio_home(request):
return render(request, 'portfolio/work.html', {'title': 'Portfolio'})
Let's say I want to pass a context (or a variable) into my base template. In this example, I want to pass title in the title tag of the head section of my base template.
In the html file for base.html, you need to have something like this:
<!DOCTYPE html>
<html lang="en">
{% load staticfiles %}
<head>
<title>{{ title }}</title>
...........
</head>
</html>
In the urls.py of my project and other apps that I want to pass a title into this, I should create the view like this:
def portfolio_home(request):
return render(request, 'portfolio/work.html', {'title': 'Portfolio'})
I found out why Django can't pass variables to HTML because;
I didn't have my apps url activated the function/model in views
I feel so embarrasses, for such simple mistakes.
All I need to do is add this code in my apps url
urlpatterns = [
path('', views.timedex, name='timedex'), #need add this
path('', views.index, name='index'),
]
Add {{block.super}} before {% endblock includes %}
Related
I'm making a site by using django. One of my models contains ImageField.
Files are saved in main_dir/media/images. I'd like to display specific images in templates but I can't achieve it. Instead of photo, I can see only default image icon which mean ( i guess ) that image is not found
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
models
class Gallery(models.Model):
name = models.CharField(max_length=200)
author = models.ForeignKey(User, on_delete=models.CASCADE, default=None, null=True, blank=True)
date_posted = models.DateTimeField(auto_now_add = True)
def __str__(self):
return self.name
class Photo(models.Model):
gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE, default=None, related_name='photos')
name = models.CharField(max_length=200)
description = models.TextField(blank=False)
image = models.ImageField(blank=True, upload_to='images')
views
def gallery(request, pk):
gallery_object = Gallery.objects.get(id=pk)
context = {'gallery':gallery_object}
return render(request, 'Gallery/gallery.html', context)
html
<!DOCTYPE html>
{% extends 'base.html' %}
{% block content %}
<h1>Gallery: {{ gallery.name }}</h1>
{% for photo in gallery.photos.all %}
<img src="{{photo.image.url}}">
<a>{{photo.image.url}}</a> #it's here only to check if path is correct
{% endfor %}
Go back to home page
{% endblock content %}
what should I change to display image correctly ?
you need to change the .get to .filter with the same condition to get multiple objects
because get will return 1 object only and you cant do the for loop in the template
There are a few things wrong. First of all, if you want to return multiple images then you have to use .filter() instead of .get() and if you are .get() instead of the filter then you don't have to loop over it as it is giving a single object. And the image is stored in Photos model and for that you will have to call that instead of gallery.
Here is how you can fix it:
For single object:
views function:
def gallery(request, pk):
gallery_object = Photos.objects.get(id=pk)
context = {'photo': photo_object}
return render(request, 'Gallery/gallery.html', context)
HTML template:
<!DOCTYPE html>
{% extends 'base.html' %}
{% block content %}
<h1>Gallery: {{ photo.name }}</h1>
<img src="{{photo.image.url}}">
<a>{{photo.image.url}}</a> #it's here only to check if path is correct
Go back to home page
{% endblock content %}
For returning multiple objects:
views function:
def gallery(request, pk):
gallery_object = Photos.objects.filter(#your query)
context = {'photos': photo_object}
return render(request, 'Gallery/gallery.html', context)
HTML:
<!DOCTYPE html>
{% extends 'base.html' %}
{% block content %}
{% for photo in photos %}
<h1>Gallery: {{ photo.name }}</h1>
<img src="{{photo.image.url}}">
<a>{{photo.image.url}}</a> #it's here only to check if path is correct
{% endfor %}
Go back to home page
{% endblock content %}
finally, i found an issue. I forgot about adding
urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
to my urls.py file.
lmao
I want to call a method in views.py from my HTML file in templates when the user is authenticated. I don't know what HTML syntax I should use here. I don't think a form or button would work since I want to simply call that method without letting the user click any button.
{% block content %}
{% if user.is_authenticated %}
<!-- I want to call the method here-->
<div id="user-logout">Hi {{ user.username }}! logout</div>
{% block chess_page %}
{% endblock %}
<!-- else redirect to the login page -->
{% else %}
<meta http-equiv="REFRESH" content="0; {% url 'login' %}">
{% endif %}
{% endblock %}
The only ways I could see this being done is either to write a custom template tag (something you should probably ask a specific question with your use case about) or use something like Ajax and POST to do something once the page is loaded with Javascript. You would want to do something like this:
This example uses JQuery
Template Code
$(document).ready(function(){
$.ajax({ url: "{% url 'thing_you_want_2_do' %}",
context: document.body,
method : "POST",
success: function(){
alert("done");
}});
});
The above code executes a POST request to the given URL.
urls.py
path('/todoitem', views.thing_you_want_to_do, name='thing_you_want_2_do'),
This just routes that request to the particular block of Python code you want to handle it.
View Code
#require_http_methods(["POST"])
def thing_you_want_to_do (request):
#do thing you want to do when the page loads
return #whatever you want to return
This does whatever it is you want to do.
I am new to django, and I see that you could create templates that you could populate in views.
You could also create some basic.htm that everyone extends...
Let say I have two pages: (django demo)
List of all questions
Detail of the question.
Now I would like to create "one page" that have first view as sidebar and another as a "detail- right" view.
I would like that on clicking on the list in sidebar change right vies.
It would be nice, if I could use different views (inside views.py) for loading separate templates.
I wish for base html would be something like this :
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Makro Zadravec</title>
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'demo/css/bootstrap.min.css.css' %}" />
</head>
<body class="body" style="background-color: #f6f6f6">
<div>
<h1> This is title</h1>
</div>
<div>
{% block sidebar %}
{% endblock %}
</div>
<div>
{% block content %}
{% endblock %}
</div>
</body>
</html>
And then I would have template for blocks:
content
sidebar
in separate views.
Apart from styling here is the logic you can follow this
as you said you already have template which already loaded list of question then your base view would return all the question object as queryset.
First of all, you don't need to write separate template because you can handle this
{% block content %}
// this will load list of all question
{% endblock %}
{% block detail %}
// here display detail of question
{% endblock %}
create two urls to hit one without kwargs and other with kwargs (if you use django version < 2.0 you need to use url instead of path)
path('target/', QuestionView.as_view(), name='target-list'),
path('target/<int:pk>', QuestionView.as_view(), name='target-detail')
Now in view file you just need to handle the kwargs:
class QuestionView(TemplateView):
template_name = "template.html"
model = Question
def get_context_data(self, **kwargs):
context = super(QuestionView, self).get_context_data(**kwargs)
context['question_list'] = #your queryset to list question#
pk = kwargs.get('pk', None) # this will return pk (id of question) if hit url otherwise None
if pk:
context['question_detail'] = #your queryset to get question-detial#
return context
so if you hit url with kwargs it will return both list of question and detail with it as context in template which you can access as below:
{% block content %}
# access question_list to list out all question
{% endblock %}
{% block detial %}
{% if question_detail %} // if question_detail context passed from view
# add detail of question by accessing question_detail
{% endif %}
{% endblock %}
You can do this based on one view.
Create variable called 'question' in your view which at start is defined as an empty string. Then if someone click on some question on sidebar block you can make url with parameter with id of question to show details ('/page/?question=1') or you can store this id in session, as you want. And call same view another time. Then in view you check if you get parameter in url or if it's stored in session and if it's true you assign question object (which you get by id) to variable 'question'. Send this variable to template. In template you render sidebar always and check if variable 'question' is not equal to empty string then you render details for question.
Something like this:
{% block sidebar %}
...
{% endblock %}
{% if question != '' %}
{% block content %}
...
{% enblock %}
{% endif %}
I am building a chatbot. There are few child templates like login.html, messages.html, transaction.html, etc. I want to append these templates in base.html dynamically. I am extending base.html in all these templates. My problem is only one template is rendered at a time. Is there any solution for appending these templates one after another? I have used {%include%} but it's a static approach. I need dynamic.
printer.py looks like -
#app.route('/respond', methods=['GET','POST'])
def respond_def():
message = request.form['message_input']
if message == "l":
return render_template('printer/login.html')
elif message == "t":
return render_template('printer/transactionID.html')
base.html looks like -
//some code here
<li>
{% block template %}{% endblock %}
</li>
//some code here
message.html looks like -
{% extends "base.html" %}
{% block template %}
<div> Message template called </div>
{% endblock %}
I resolved it.
I made a list of templates in printer.py and then appended those templates in base.html whenever user asked for it.
printer.py
dictionary = []
// append name of template in this whenever needed.
return render_template('printer/base.html', dictionary=dictionary)
base.html
{% for d in dicts %}
{% set template = 'printer/' + d + '.html' %}
// can add conditions for different templates
{% include template %}
{% endfor %}
I have a problem to send json data using django templates to the front (html).
This is the python code:
#api_view(['GET'])
#renderer_classes((JSONRenderer,))
def tasks_list_all(request):
i = inspect()
tasks_dic=i.registered_tasks()
for cle in tasks_dic.keys():
key=cle
tasks_old_v=tasks_dic.get(key)
tasks_new_v=[]
for tasks in tasks_old_v:
new_tasks=tasks.replace('infra_mngt.tasks.','')
tasks_new_v.append(new_tasks)
add_new=tasks_new_v[-1].replace('provisionning.celery.','')
tasks_new_v[-1]=add_new
tasks_new_v_new=json.dumps(tasks_new_v)
print "json.dumps(tasks_new_v)",tasks_new_v_new
#~ return render(request, os.path.join(settings.BASE_DIR, 'infra_mngt', 'templates', 'tasks_all.html'), context={'list':tasks_new_v})
#~ return render(request, os.path.join(settings.BASE_DIR, 'infra_mngt', 'templates', 'tasks_all.html'),{'list':tasks_new_v})
return render(request, os.path.join(settings.BASE_DIR, 'infra_mngt', 'templates', 'tasks_all.html'),{'list':tasks_new_v_new})
this is the code of the front (tasks_all.html):
<h1>Dynamic list tasks</h1>
{% for list in tasks_new_v_new %}
{{ list }}
{% endfor %}
But after execution, I don't get any elements of the list that I need, just the display of this html code:
<h1>Dynamic list tasks</h1>
you're passing the wrong context to the template (or you're using the wrong variable in the template)
try something like (in the view):
return render(request, your_template, {"tasks": tasks_new_v_new})
in the template:
{% for task in tasks %}
{{ task }}
{% endfor %}
notice I'm passing a variable called tasks to the template and in the template I'm looping that variable.
Hope this helps