Displaying Django DB values on index.html original path - django

I have a DB hat hs some values in it. I want to display these values on my index.html. i want to display them on the standard html path path('', views.index, name = "index"),
I currently displaying them at path('this_is_the_path/', my_db_class.as_view()),
The problem is that i am pulling the values from a class. and i can't figure out how to set the class to the original index.html path.
Models.py
from django.db import models
class Database(models.Model):
text = models.TextField()
Views.py
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Database
# Create your views here.
def index(request):
return render(request,"index.html",{})
class my_db_class(ListView):
model = Database
template_name = 'index.html'
URLS.PY
from django.urls import path
from . import views
from .views import my_db_class
urlpatterns = [
path('', views.index, name = "index"),
path('this_is_the_path/', my_db_class.as_view()),
]
HTML.PY
<ul>
{% for post in object_list %}
<li> {{ post.text }}</li>
{% endfor %}
</ul>
So my problem is that the above code will only show my DB values at the this_is_the_path path, but i want to show it at the '' path.

just modify your index function like this.
views.py
def index(request):
object_list = Database.objects.all()
return render(request,"index.html",{'object_list':object_list})

Related

How to Load multiple Model to single template in Django 2

How to load multiple models in one template in Django 2?
i've read Django Pass Multiple Models to one Template but, i'm lost in the answer and there is no specific answer there to get that view into the template,
Im trying to pass 3 models in views to template, which is Info, Slogan & Berita.
My views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Artikel, Berita, Data, Galeri, Info, Slogan, Profil
from django.views.generic import ListView, DetailView
def home(request):
extra_context : {"info" : Info.objects.all(),
"slogan": Slogan.objects.all(),
"berita": Berita.objects.all(),
#and so on for all the desired models...
}
return render (request, 'blog/home.html')
class HomeListView(ListView):
context_object_name = 'slogan'
template_name = 'blog/home.html'
queryset = Info.objects.all()
def get_context_data(self, **kwargs):
context = super(HomeListView, self).get_context_data(**kwargs)
context['slogan'] = Slogan.objects.all()
context['berita'] = Berita.objects.all()
# And so on for more models
return context
my template home.html looks like:
{% for slogans in slogan %}
<p>{{ slogans.konten }}</p>
<p>{{ slogans.author }}</p>
{% endfor %}
my url urls.py looks like:
from blog.views import HomeListView
urlpatterns = [
url(r'^$', HomeListView.as_view(), name="home"),
]
and page source on browser shows nothing.
Im stuck on this, i found at least 3 similar result on this site but not works for me.

django forms {{from.as_p}} not rendering any text box or input

I'm sorry to ask something simple, but i'm just trying to add forms into my Django project
I'm just following this tutorial on forms, from:
https://www.youtube.com/watch?v=6oOHlcHkX2U&t=115s
Here's my form in HTML
<div class="form-popup" id="myForm">
<form class="form-container" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="add">
<button type="button" class="btn cancel" onclick="closeForm()">Close</button>
</form>
</div>
Here's my code in forms.py:
from django import forms
from .models import Stream
class CameraForm(forms.ModelForm):
class Meta:
model = Stream
fields = (
'name',
'RTSP',
)
my views.py
from django.shortcuts import render, get_object_or_404
from CGI.models import tank_system, ambient, Limit
from CGI.basicfun import selectDates, weekSelect
import logging
logger = logging.getLogger(__name__)
from .forms import CameraForm
def index(request):
forms = CameraForm(request.POST or None)
if forms.is_valid():
forms.save()
tank = tank_system.objects.latest('datetime')
room = ambient.objects.latest('datetime')
limit, created = (Limit.objects.get_or_create())
return render(request, 'CGI/Pages/DashBoard.html', {'tank':tank,'room':room, 'limit':limit, 'form':forms})
Here my Models:
from django.db import models
from django.utils import timezone
class tank_system(models.Model):
... #my tank tables
class ambient (models.Model):
... #my room tables
class Limit (models.Model):
... #my limit tables
# here the class that use in the forms
class Stream (models.Model):
name = models.CharField(max_length=30)
RTSP = models.CharField(max_length=200)
My apps URL
urlpatterns = [
path(r'',login_required(views.index), name='index'),
path(r'^Water-data-chart/',login_required(views.Lquid), name='tank'),
path(r'^Ambient-data-chart/',login_required(views.Ambient), name='room'),
path(r'Rest-api/', include(router.urls))
]
My project URL
urlpatterns = [
path(r'admin/', admin.site.urls),
path(r'accounts/', include('django.contrib.auth.urls')),
path(r'api-auth/', include('rest_framework.urls'), name='rest_framework'),
path(r'', include('CGI.urls')),
]
Now problems is {{from.as_p}} is supposed to create an html text box form me input and post which ever data,
(here how its support to look: )
but when I open up local test, I see nothing,
Here What I see:
leaving me stumped and confused.
I really appreciate if you could help.

django DetailView how to show the details page

I want to show the details of a product added.
I followed this link and i could create an add product page
https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html
once the product is added, i want to show the details of the product added in a new page.
So i tried the following:
class ProductDetailView(DetailView):
model = Product
context_object_name = 'product'
queryset = Product.objects.filter(pk)
I really don't know what to put in the filter, or using filter is correct. i had tried using latest and order by instead of filter but they did not work.
my urls.py is as follows:
urlpatterns = [
path('', views.ProductDetailView.as_view(), name='product_changelist'),
#path('', views.ProductListView.as_view(), name='product_changelist'),
path('add/', views.ProductCreateView.as_view(), name='product_add'),
path('<int:pk>/', views.ProductUpdateView.as_view(), name='product_change'),
path('ajax/load-subcategory/', views.load_subcategory, name='ajax_load_subcategory'),
#path('<int:product_id>', views.detail, name='detail'),
]
Currently i am getting error as
AttributeError at /product/
Generic detail view ProductDetailView must be called with either an object pk or a slug.
I read that we have to provide the pk in urls.py so i tried providing pk as follows:
path('<int:pk>', views.ProductDetailView.as_view(), name='product_changelist'),
but then i get an error as follows:
NoReverseMatch at /product/add/
Reverse for 'product_changelist' with no arguments not found. 1 pattern(s) tried: ['product\\/(?P<pk>[0-9]+)$']
Any help in solving this problem is highly appreciated. I am new to django so may have done many mistakes above.
Edit 1:
I tried the suggestion given by #Radico, but still the same error: What i did is as follows:
Changed my ProductDetailView as follows:
class ProductDetailView(DetailView):
model = Product
context_object_name = 'product'
the product_list.html now has the following content
{% extends 'base.html' %}
{% block content %}
<br />
<br />
<br />
<br />
<br />
This is the page getting displayed121
{% url 'product_changelist' pk=object.pk %}
{% endblock %}
Still i get the same error as
AttributeError at /product/
Generic detail view ProductDetailView must be called with either an object pk or a slug
I did not change anything in urls.py.... do i have to change anything in it as well?
Edit 2:
Here is my urls.py
from django.urls import include, path
from . import views
urlpatterns = [
path('<int:pk>', views.ProductDetailView.as_view(), name='product_changelist'),
#path('', views.ProductDetailView.as_view(), name='product_changelist'),
#path('', views.ProductListView.as_view(), name='product_changelist'),
path('add/', views.ProductCreateView.as_view(), name='product_add'),
path('', views.ProductUpdateView.as_view(), name='product_change'),
path('ajax/load-subcategory/', views.load_subcategory, name='ajax_load_subcategory'),
#path('<int:product_id>', views.detail, name='detail'),
]
My views.py is as follows:
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView, UpdateView, ListView, DetailView
from category.models import Subcategory
from product.forms import ProductForm
from product.models import Product
class ProductListView(ListView):
model = Product
context_object_name = 'product'
queryset = Product.objects.filter()
class ProductDetailView(DetailView):
model = Product
context_object_name = 'product'
# queryset = Product.objects.filter()
# class ProductDetailView(DetailView):
# template_name = 'product/product_list.html'
# #model = User
# #context_object_name = 'foo'
#
# def get_object(self):
# #return get_object_or_404(Product, pk=request.session['product_id'])
# return get_object_or_404(Product, pk=self.request.
class ProductCreateView(CreateView):
model = Product
form_class = ProductForm
success_url = reverse_lazy('product_changelist')
def productlist(request, product_id):
product = Product.objects.get(productid=product_id)
return render(request, 'product/product_list.html', {'product': product})
# def productlist(request):
# prodlist = Product.objects.order_by('-pk')[0]
# return render(request, 'product/product_list.html', {'prodlist': prodlist})
class ProductUpdateView(UpdateView):
model = Product
form_class = ProductForm
success_url = reverse_lazy('product_changelist')
def load_subcategory(request):
category_id = request.GET.get('category')
subcategory = Subcategory.objects.filter(category_id=category_id).order_by('name')
return render(request, 'product/subcategory_dropdown_list_options.html', {'subcategory': subcategory})
My product_list.html is as i had pasted earlier
{% extends 'base.html' %}
{% block content %}
<br />
<br />
<br />
<br /><br />
This is the page getting displayed121
{% url 'product_changelist' pk=object.pk %}
{% endblock %}
First: You don't need to get query set within the detailview the object is already available, you can call it in the template object or class name lowercase in your case product.
Second: make sure that you pass pk in urls refer to the detailview within templates i.e {% url 'product_change' pk=object.pk %}
I believe you got the error for second part check the url in product_changelist template and you may forgot to pass pk=object.pk
If you want to use Regular expressions when you're using path:
from django.urls import path , re_path
re_path(r'^product/(?P<pk>\d+)$', views.ProductUpdateView.as_view(), name='product_change'),

django template import url tags is there a better way?

My goal is to list a few links in a page and I was wondering if there's a better way of do this line of code:
<a href={% url ''|add:app_name|add:':'|add:model_name|add:post_fix %}> {{ model_name }} </a>
This part : ''|add:app_name|add:':'|add:model_name|add:post_fix
-- If so, what is the flaw in my thinking, is it the URL-name, or doing too much in the template, or something else? Should I do the construction in python code in view.py, if so can you show me how you would tackle this problem?
a_template.html
{% for model_name in list_model_names%}
....
<a href={% url ''|add:app_name|add:':'|add:model_name|add:post_fix %}> {{ model_name }} </a>
....
{% endfor %}
url.py
from django.conf.urls import url
from . import views
app_name = 'app'
urlpatterns = [
url(r'^stone/$, view.....as_view(), name='stone_index'),
url(r'^cloud/$', view.....as_view(), name='cloud_index'),
]
views.py
from django.shortcuts import render_to_response
from django.views import View
from app.models import (Stone, Cloud)
class ThisView(View):
template_name = 'app/a_template.html'
models = [Stone, Cloud]
model_names = [model._meta.model_name for model in models]
app_name = 'app'
post_fix = '_index'
dict_to_template = {'app_name': app_name,
'list_model_name': model_names,
'post_fix': post_fix}
def get(self, *args, **kwargs):
return render_to_response(self.template_name, self.dict_to_template)
Thank you for your time.
It would be tidier to reverse the urls in the template
from django.urls import reverse . # Django 1.9+
# from django.core.urlresolvers import reverse # Django < 1.9
model_names = [model._meta.model_name for model in models]
app_name = 'app'
post_fix = '_index'
urls = [reverse('%s:%s%s' % (app_name, model, post_fix)) for model in model_names
Then zip the model names and urls together and include them in the template context:
models_and_urls = zip(model_names, urls)
dict_to_template = {'models_and_urls: models_and_urls}
You can then loop through the model names and urls in your template.
{% for model_name, url in models_and_urls %}
....
{{ model_name }}
....
{% endfor %}

django views connecting to model and urls

I am writing my first views in Django. I have spent countless hours trying to figure this out. One of my views appears in the web page, but the other one that I am trying to retrieve data from the database is not. I've used the python shell to see if the code works and it does. The following is my model, view, my urls, and template. Additionally, any documentation websites would be great too - or books. thanks all.
models.py
from django.db import models
class Bee_hive(models.Model):
gid = models.IntegerField(primary_key=True)
hive_title = models.CharField(max_length=50)
date_hive_death = models.DateField()
date_hive_created = models.DateField()
description = models.TextField()
def __str__(self):
return self.hive_title
views.py
from django.shortcuts import render
import datetime
from inventory.models import Bee_hive
def index(request):
now = datetime.datetime.now()
context = {'current_date': now}
return render(request, 'inventory/index.html', context)
def hive_names(request):
titles = Bee_hive.objects.all()
context = {'titles': titles}
return render(request, 'inventory/index.html', context)
My template contains the following:
<html>
<body>
<p>Hello, David!</p>
It is now {{ current_date }}.
<p>The hive name is: {{ titles }} </p>
</body>
</html>
urls.py
from django.conf.urls import patterns, url
from inventory import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^$', views.hive_names, name='hive_names'),
)
This is my result:
Hello, David!
It is now Jan. 18, 2015, 7:08 a.m..
The hive name is:
You should set different urls to different views:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^hive-names/$', views.hive_names, name='hive_names'),
)