I have created a project named Test and an app named testing inside this app. I have a model named ModelTesting in the testing app. This model has only one field named prop, which is a CharField of max_length=20. I can insert the items in database without any issue but cannot display them in the homepage. Take a look at my code.
Here is my models.py
from django.db import models
# My Model
class ModelTesting(models.Model):
prop = models.CharField(max_length = 20)
def __str__(self):
return self.prop
Here is my views.py
from django.shortcuts import render
from .models import ModelTesting
# Loads Homepage
def index(request):
all_testing_models = ModelTesting.objects.all()
params = {'all_models': all_testing_models}
return render(request, "index.html", params)
And here is the bootstrap template in which I want to display the items. Also, I have edited the template myself.
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/css/bootstrap.min.css" integrity="sha384-VCmXjywReHh4PwowAiWNagnWcLhlEJLA5buUprzK8rxFgeH0kww/aWY76TfkUoSX" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<h1>The Properties are:-</h1>
{% for test_model in all_testing_mdoels %}
<h3>{{test_model.prop}}</h3>
{% endfor %}
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/js/bootstrap.min.js" integrity="sha384-XEerZL0cuoUbHE4nZReLT7nx9gQrQreJekYhJD9WNWhH8nEW+0c5qq7aIo2Wl30J" crossorigin="anonymous"></script>
</body>
</html>
This error has occurred in some other projects as well, so I created this project specifically for this purpose. Please take a look and help me.
Thank You.
You're doing all_models in
params = {'all_models': all_testing_models}
and trying to look for all_testing_models in
{% for test_model in all_testing_mdoels %}
<h3>{{test_model.prop}}</h3>
{% endfor %}
Fix either one to match the other.
You may wish to turn on string_if_invalid to help you catch typos better.
Related
I need help with my code, I'm making a form in django and I can't solve this error.
views.py:
def ferrocarrilFormulario(request):
if request.method =="POST":
miFormulario = ferrocarrilFormulario(request.POST)
print(miFormulario)
if miFormulario.is_valid:
informacion = miFormulario.cleaned_data
ferrocarril = ferrocarril(request.POST["tipo"], request.POST["precio"])
ferrocarril.save()
return render (request, "AppCoder/inicio.html")
Forms.py:
from django import forms
class ferrocarrilFormulario(forms.Form):
tipo= forms.CharField()
precio = forms.IntegerField()
Form 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">
<title>Agrega un ferrocarril</title>
</head>
<body>
{% if.miFormulario.errors %}
<p style="color: red;"> Datos mal ingresados</p>
{% endif %}
<form action="" method="POST"{% csrf_token %}
<table>
{{ miFormulario.as_tabble }}
</table>
<input type="submit" value="Enviar">
></form>
</body>
</html>
urls.py:
from django.urls import path
from AppCoder import views
urlpatterns = [
path('',views.inicio, name="Inicio"),
path("ferrocarril/", views.ferrocarril, name="ferrocarril"),
path("vias/", views.vias, name="vias"),
path("manodeobra/", views.manodeobra, name="manodeobra"),
path("tables.html/", views.tables, name="tables"),
path("ferrocarrilFormulario/", views.ferrocarrilFormulario, name="ferrocarrilFormulario")
thank you <3
I wanted the form to work after that, but that is not the case.
PS: if I put the request, it generates another error, and in the tutorial it appears without the request.
Thanks again.
I wanted Pass URL parameter in iframe issue as mentioned Passing URL parameter in iframe issue
I tried using following https://glitch.com/edit/#!/tf-embed-with-params?path=README.md:1:0
Traceback:
Exception Type: AttributeError
Exception Value:
'RequestContext' object has no attribute 'META'
views.py
from django.shortcuts import render
from django.template import RequestContext
def survey(request):
return render(RequestContext(request),'wfhApp/survey.html')
And my html page is as follow:
<!DOCTYPE html>
{% load django_typeform %}
{% load sekizai_tags %}
<html>
<head>
<title>Hello!</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<h1>Hi there!</h1>
<div class="target-dom-node" style="width: 100%; height: 500px;"></div>
<script src="https://embed.typeform.com/embed.js"></script>
<script src="/survey/script.js"></script>
{% typeforms_embed 'https://theother2thirds.typeform.com/to/hNZW30' 'New typeform' '{"hideHeaders": true, "hideFooter": true}' %}
</body>
</html>
urls.py
from django.conf.urls import url
from wfhApp import views
app_name = 'wfhApp'
urlpatterns = [
url(r'^survey/$',views.survey, name='survey'),
]
The issue is that you're wrapping the request inside of a RequestContext object, which is incorrect for the render() function.
The render() function will build the RequestContext object for you, so it expects the request and any extra context variables as arguments.
Instead, just pass the request directly to the render() function:
def survey(request):
return render(request, 'wfhApp/survey.html')
I want to create different templates, but both of them share almost the same attributes. For example, both the blog page and the movie page have the model 'Post' that allows users to add new Articles/Movies to the Website.
Also, I assume that the 'Movie - Post' model would need different fields than the 'Article - Post' model, but they still share many of them.
Someone can help me how to implement that out?
There are two possible ways to do this.
1. Make an outer file and insert all your code into the inner file. This uses extends.
The outer file, base.html
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
</head>
<body>
<p> You can also put anything else you want on every page here.</p>
<main role="main" class="container">
{% block content %}
{% endblock %}
</main>
</div>
</body>
</html>
The inner file, page.html
{% extends 'base.html' %}
{% block content %}
<p>This is the stuff you want to be unique to the page. </p>
{% endblock %}
The disadvantage of this method is that you are essentially putting one page inside another and it is a little less flexible.
2. Include the chunk of code inside an HTML file. This uses include.
The page you want to add the header to, page.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
</head>
<style>
body { padding-top: 70px;
font-family: Poppins;
}
</style>
<body>
{% include "header.html" %}
<main role="main" class="container">
<p> Whatever you want on your page</p>
</main>
</div>
</body>
</html>
The actual code for your header, header.html
<div class="header">
<p>My supercool header</p>
</div>
Include will insert that block of HTML code right where you put the include statement.
With regard to the models with common elements, you can do something like this:
from django.db import models
class CommonInfo(models.Model):
#common fields go here
post = models.CharField(max_length=100)
class Meta:
abstract = True
class Blog(CommonInfo):
#fields unique to blog go here
name = models.CharField(max_length=5)
class Movie(CommonInfo):
#fields unique to movie go here
name = models.CharField(max_length=5)
I am building a blog website where I can upload audio/video files to the database and then run a for loop to output the files in HTML audio/video tags. I have succeeded in saving the files to the database and also output them on the website but for some reason I can't get them to play.
I am still pretty new to Python/Django and I would appreciate it if anybody can help me figure this one out. Thanks in anticipation
Here is my models.py
from django.db import models
class Track(models.Model):
track_title = models.CharField(max_length=250)
track = models.FileField(upload_to='album/')
def __str__(self):
return self.track_title
Here is my index.html
{% load static %}
<!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>Document</title>
</head>
<body>
{% for track in tracks %}
<figure>
<figcaption>Audio</figcaption>
<audio controls>
<source src="{{ track.track.url }}" type="audio/mp3">
</audio>
</figure>
{% endfor %}
This is my views.py
from django.shortcuts import render
from .models import Track
def songView(request):
tracks = Track.objects.all()
context = {
'tracks':tracks
}
return render(request, 'album/index.html', context)
And my urls.py
from django.urls import path
from . import views
app_name = 'album'
urlpatterns = [
path('', views.songView, name='song'),
]
I am new to Django. I want to draw a google graph using django graphos. I have written small code for that and i am getting empty template..any lead would be appritiated..
view.py
from graphos.renderers import gchart
from django.shortcuts import render
from django.shortcuts import render_to_response
from graphos.sources.model import ModelDataSource
from models import MyCityViews
def get_context_data(self):
queryset = MyCityViews.objects.all()
data_source = ModelDataSource(queryset,fields=['city', 'views'])
line_chart = gchart.LineChart(data_source)
context = {"chart": line_chart}
return render_to_response('gchart.html', {'chart': line_chart})
models.py
from django.db import models
# Create your models here.
class MyCityViews(models.Model):
city = models.CharField(max_length = 30, blank = True , null = True)
views = models.IntegerField()
class Meta:
ordering = ['city']
verbose_name = 'city'
verbose_name_plural = 'city'
def __unicode__(self):
return self.city
gchart.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>Graphos</title>
{% load static from staticfiles %}
<link rel="stylesheet" href="{% static "css/bootstrap.css" %}">
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback({{line_chart.as_html}});
</script>
</head>
<body>
{{line_chart.as_html}}
<div id="container"></div>
</body>
</html>
Where i am doing wrong...
Did not pass view object to div block thats why i was not getting HTML view.
<body>
<div id="container">
{{line_chart.as_html}}
</div>
</body>