Access a single object from Database ListView using Django - python

I have a class that passes in a django ListView. From this ListView I can access my DB items. My problem is that accessing the db using the list view will load all the entries. what if I just want one entry, say the 5th entry for example. Maybe listView is the wrong type of view to be using? my code below work and shows my DB entries on-screen as a list.
models.py
from django.db import models
class Datadata(models.Model):
text = models.TextField()
views.py
class HomePageView(ListView):
model = Datadata
template_name = 'hello.html'
templates/hello.html
{% for post in object_list %}
<h1>{{ post.text }}</h1>
{% endfor %}

Then you normally use a DetailView [Django-doc]. You can for example define this as:
from django.views.generic.detail import DetailView
class HomePageView(DetailView):
model = Datadata
template_name = 'hello.html'
You can then render this for example with:
<h1>{{ object.text }}</h1>
What is convenient is that a DetailView, just like all views with a SingleObjectModelMixin [Django-doc] autoamtically filter on the primary key pk or slug field.
So the url pattern should look like:
urlpatterns = [
path('data/<int:pk>/', HomePageView.as_view(), name='data-detail'),
]
If we then access /data/5 for example, it will show the data for the item with as primary key 5.

Related

Django: List and Display Data from DB

I found a code that the urls in django can contain a model, so it can display a db values directly to html, but when i tried it, i got some error in the urls because this code still using patterns, is it possible doing this thing in a newer django?
The Url
from django.views.generic import ListView
from django.conf.urls import patterns, url
urlpatterns = patterns("myapp.views",
url(r'^dreamreals/', ListView.as_view(
template_name = "dreamreal_list.html")),
model = Dreamreal, context_object_name = ”dreamreals_objects” ,)
The HTML
{% extends "main_template.html" %}
{% block content %}
Dreamreals:<p>
{% for dr in object_list %}
{{dr.name}}</p>
{% endfor %}
{% endblock %}
I'm pretty sure all you've entered are kwargs of ListView.as_view() method.
So instead of doing
ListView.as_view(
template_name = "dreamreal_list.html")),
model = Dreamreal, context_object_name = ”dreamreals_objects” ,)
Which is actually syntaxly incorrect, do :
ListView.as_view(
template_name = "dreamreal_list.html",
model = Dreamreal,
context_object_name = ”dreamreals_objects”
)
Second error, you're setting the context_object_name to dreamreals_objects, but in your template you're iterating over object_list.
But this method is not really "pretty" and you should really make a views.py with your views and then the urls.py should only care about making a route.
As pointed in comments, django 2.1+ no longer use urlpatterns but path : https://docs.djangoproject.com/en/2.1/topics/http/urls/#example

How do create a link from a database in Django?

If you have a blog model in Django that saves a slug, how do you create an href link from that slug field?
You should create a view according to Django MVT architecture.
For example you can create a DetailView and associate it with an URL.
# views.py
from django.views.generic.detail import DetailView
from someapp.models import SomeModel
class SomeModelDetailView(DetailView):
model = SomeModel
# urls.py
from django.conf.urls import url
from someapp.views import SomeModelDetailView
urlpatterns = [
url(r'^(?P<slug>[-\w]+)/$', SomeModelDetailView.as_view(), name='somemodel-detail'),
]
And just use the {% url %} template tag to access to this page. For example :
{{ foo.name }}
Where foo is a SomeModel instance.

In django, how generic view works

I have started learning django, I'm not sure how generic view works. I read django documentation several times, I can't gain clear understanding of how generic view works. Very strange but it works well. It retrieves data from the database and renders data on the browser.
Here is snippet code of polls/urls.py.
url(r'^$', views.IndexView.as_view(), name = 'index')
It will go to the IndexView class in views.py.
Here is snippet code of polls/views.py.
from django.views import generic
from .models import Question, Choice
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
return Question.objects.order_by('-pub_date')[:5]
When I change template_name as something, the exception has occurred as follows.
TemplateDoesNotExist: polls/question_list.html
What does question_list.html mean?
Where does it come from?
And here is index.html.
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li>
{{ question.question_text }}
</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
As you can see, index.html file use latest_question_list as a parameter but I'm not sure how can the latest_question_list be used.
In views.py file, what does context_object_name = 'latest_question_list' mean?
Where does the 'latest_question_list' come from and how can index.html use latest_question_list?
Do I use context_object_name in views.py?
What's the role of the get_queryset() function?
What does question_list.html mean?
It means that there is a file inside polls dir like index.html
if you want to have a file with a diff name you have to change the name of template_name='polls/name_of_file_inside_polls'
Do I use context_object_name in views.py?
The context is the place where you put some vars to use it in your templates, that's why you can use latest_question_list
What's the role of the get_queryset() function?
It creates the query that is passed to the template.
I understand what they mean.
By default, the DetailView generic view uses a template called /_detail.html. In my case, it would use the template "polls/question_detail.html". The template_name attribute is used to tell Django to use a specific template name instead of the autogenerated default template name. I also specify the template_name for the results list view – this ensures that the results view and the detail view have a different appearance when rendered, even though they’re both a DetailView behind the scenes.
For DetailView the question variable is provided automatically – since we’re using a Django model (Question), Django is able to determine an appropriate name for the context variable. However, for ListView, the automatically generated context variable is question_list. To override this we provide the context_object_name attribute, specifying that we want to use latest_question_list instead.

Detail template in Django not taking values

from django.views import generic
from .models import Inspectionfile
from .models import posts
class IndexView(generic.ListView):
template_name = "posts/index.html"
def get_queryset(self):
return Inspectionfile.objects.all()
class DetailView(generic.DetailView):
model = Inspectionfile
template_name = "posts/detail.html "
#index template
<ul>
{% for o in object_list %}
<li>{{o.document_title}} </li>
{% endfor %}
</ul>
#detail template
<h1>{{ o.document_title }}</h1>
My Index template works but the detail template does not seem to take the value so just appears blank . So is the 'o' not being passed to detail ?? I have not been able to solve this. BTW document_title is one of the field of my inspectionfile model. I checked my url regex and it seems to work fine.
o is an object which only exists within the for loop in your list view template. It isn't passed anywhere.
The detail view has its own context; there the object that is identifued by the url argument is called just object.

DetailView not showing data

I am trying to display a ListView of items that when clicked opens the respective DetailView for that item. This is a pretty straightforward thing to do in Django, but I'm running into some trouble with it.
I have successfully created a ListView, but I can't get the DetailView to display the information for each item.
I am building a password safe. The ListView lists all the passwords saved, and the DetailView is the view/edit page for each password. And yes, I realize actually putting a password safe on the internet is a terrible idea, it's just a test project :)
My PasswordSafe class:
class PasswordSafe(models.Model):
user = models.OneToOneField(User)
pwWebsite = models.CharField(max_length=30)
pwUsername = models.CharField(max_length=30)
pwEmail = models.CharField(max_length=30)
pwPassword = models.CharField(max_length=30)
def __unicode__(self): # __unicode__ on Python 2, __str__ on Python 3
return self.pwWebsite
User.passwordSafe = property(lambda u: PasswordSafe.objects.get_or_create(user=u)[0])
My urls.py:
from django.conf.urls import patterns, include, url
from django.views.generic import ListView, DetailView
from models import PasswordSafe
urlpatterns = [
url(r'^passwordSafe/$', ListView.as_view(queryset=PasswordSafe.objects.all().order_by('-pwWebsite')[:10], template_name = 'userprofile/passwordSafe_list.html')),
url(r'^passwordSafe/(?P<pk>\d+)/$', DetailView.as_view(model=PasswordSafe, template_name='userprofile/passwordSafe.html')),
]
I use the following code successfully in my ListView template (passwordSafe_list.html):
{% for passwordSafe in object_list %}
<h2>{{ passwordSafe.pwWebsite }}</h2>
{% endfor %}
However, when I try to use the passwordSafe data in my Detailview (the passwordSafe.html template), nothing shows up. I use the following code to try and change the title:
<title>{% block title %} | Edit {{ passwordSafe.pwWebsite }} Password{% endblock %}</title>
This should show a title something like "Password Safe | Edit Google Password", but passwordSafe.pwWebsite returns with nothing. Am I doing something wrong in trying to reference passwordSafe from this template? I know I haven't passed a query set like I did with the ListView, but I'm not sure if that's part of the problem or not.
In the DetailView, Django uses the model name in lowercase, by default, if you haven't set context_object_name.
{{ passwordsafe.pwWebsite }}

Categories

Resources