How to use the querylist object in Django template - django

Initially i had this code
(r'^list/fixed/$', list_detail.object_list, fixedList)
In template i use
{% for val in object_list %}
It worked fine as i used Generic list
But now i want to write my own view which does same
object_list = model.objects.all()
return render_to_response('lists.html', object_list)
But its not working.
how can pass the same object list to template as in Generic View

render_to_response() takes a dictionary of variables to use.
return render_to_response('lists.html', {'object_list': object_list})

Related

How should I understand below codes in Django?

1. define a class in the models.py which was created in my own app.
class Article(models.Model):
headline = models.CharField(null=True,blank=True,max_length=200)
content = models.TextField()
def __str__(self):
return self.headline
2. define a function in views.py
from firstapp.models import People,Article
def index(request):
article_list = Article.objects.all()
context = {}
context['article_list'] = article_list
index_page = render(request, 'first_web_2.html', context)
return index_page
The question is: Is the article_list a list?how should I understand "context['article_list'] = article_list"?
Variable article_list is a queryset, which is a collection of objects from your database stemming from the query Article.objects.all(). This particular query is much like SELECT * FROM Article.
The context is a dictionary where string 'article_list' is the key and the variable article_list is the value. The context is passed to your template via the render method where the key is used in your template to render the associated value.
Since you are passing a collection you would have to perform a loop on it in your template. For example, this would render an unordered list of headlines. Note the use of the dot operator to access headline.
<ul>
{% for a in article_list %}
<li> {{ a.headline}} </li>
{% endfor %}
</ul>
article_list is not a list, it's a QuerySet. QuerySets are representations of SQL queries via Django's Object Relational Mapper (ORM). It's easy to see them as lists but they are quite different. In any case, you should read Django's documentation about them.
As for context, you can think of it as passing variables that you can access in your templates. It could be strings, numbers, lists, QuerySets, dictionaries etc. In this case, you want to be able to access your all your Articles in the template, likely so that you can loop through them like {% for article in article_list %}. This allows you to then call the attributes like article.headline and article.content in your template.
QuerySet's in Django are iterable so article_list is not directly a list.
context['article_list'] = article_list
context is an dict and the entry 'article_list' is sign to the query result article_list.
In the template you can get access to the query set like
{% for article in article_list %}
{{ article }}
{% endfor %}
You question is hard to understand but I think I got the right answer. You need to read the framework documentation to understand "what that mean":
context: https://docs.djangoproject.com/en/2.0/ref/templates/api/#django.template.Context
queryset (the list) : https://docs.djangoproject.com/en/2.0/ref/models/querysets/#when-querysets-are-evaluated

How can I tell if I'm doing a create or an update with django generic views (CreateView vs UpdateView) from my template?

I'm sharing the same template for my CreateView and UpdateView using django's generic views. I want the "submit" button in my template to say "Add" when I'm using the CreateView and "Update" when I'm using the UpdateView. Is there any way in my template to distinguish which view is being used (CreateView vs UpdateView)?
I know I could use a separate template using template_name_suffix and put the common stuff in a separate include or something but just wanted to see if there was a way to do it without creating a separate template.
When creating a new object, object will always be None, at the moment the template is rendered. You could check for the existence of {{ object }} in your template:
{% if object %}Update{% else %}Add{% endif %}
Override get_context_data and add a flag in your view:
def get_context_data(self, **kwargs):
context = super(YourClass, self).get_context_data(**context)
context['create_view'] = True
return context
Change YourClass to your Class View name
Then in your template you can:
{% if create_view %}

Django basics: how to render a context with a class based view

My 'Note' model has a Charfield called 'tags'. I want to take the Note.tags string and render it as a . I have a method that will give me a python list and I am sort of hoping that I can use the form method '.as_ul' in the template. But I can't seem to get the variable into the template. Here is what I am trying:
My view class:
import string
...
class NoteDetailView(generic.DetailView):
model = Note
template_name = 'note_taker/note'
def tag_string_to_list(self):
tag_string = Note.tags
tag_list = string.split(tag_string)
return render(template_name, Context({'tag_list':tag_list}, note_taker))
My template:
<ul>
{{ tag_list.as_ul }}
</ul>
even if I am wrong about how to use '.as_ul' I can't even render the list with {{ tag_list }}
I suppose I am not understanding how view methods work then.
Use the get_context_data method.
class NoteDetailView(generic.DetailView):
def get_context_data(self, **kwargs):
context = super(NoteDetailView, self).get_context_data(**kwargs)
context['tag_list'] = Note.tags.split()
return context
Within the template, you won't be able to use .as_ul, but there is a built in filter unordered_list that will probably do what you want:
<ul>
{{ tag_list|unordered_list }}
</ul>
Although you should really consider defining a standalone Tag model and using a many-to-many relationship rather than just a char field. This is one of the classic examples of many-to-many relationships. Or using one of the third-party Django tagging packages.
I always use Django's standard ContextMixin. It makes sure that the view object is available in the template as view.
So the view becomes like
class NoteDetailView(generic.ContextMixin, generic.DetailView):
model = Note
template_name = 'note_taker/note'
def tag_string_as_list(self):
return Note.tags.split()
And in the view you do:
<ul>{{ view.tag_string_as_list }}</ul>

Loading template tag variables for use in template

How do I load the results of a templatetag into a a template to iterate over? Basically I am aiming to load the tags on a model object (using django-tagging) and then iterate through the tags to create a list of related products based on those tags. Then I would like to iterate through those product objects to display more information about them.
Ex, my template tag:
#register.simple_tag
def get_rel_from_tag(tag_list):
try:
relproducts = UniPart.objects.filter(part__contains = partbase)
except:
print "no related products"
return None
else:
relproducts = UniPart.objects.filter(part__contains = partbase)
return relproducts
How do I make it so that relproducts is returned as a variable? This is how I call it in the template:
{% tags_for_object design as tag_list %}
{% get_rel_from_tag tag_list %}
Basically now I want to iterate over relatedprod now but it's not working.
The simple_tag helper does not allow you to assign the result to a context variable in this way. Try using assignment_tag instead.
Did you load the template tag file using {% load 'your_file_name %}
Update:Try using 'with' to cache the result from tags_for_object_design
{% with tag_list=tags_for_object design %}

Sending an object with request

In the below code i am trying to send a object with the request,Is this correct if so how to decode it in template
def index(request):
cat = Category.objects.filter(title="ASD")
dict = {'cat' : cat}
request.update('dict' : dict)
#or
request.dict=dict;
And In the templates can we write the code as
{% for obj in request.dict%}
obj.title
{% endfor %}
EDIT:
If i am calling function like
def post_list(request, page=0, paginate_by=20, **kwargs):
logging.debug("post_list")
page_size = getattr(settings,'BLOG_PAGESIZE', paginate_by)
return list_detail.object_list(
request,
queryset=Post.objects.published(),
paginate_by=page_size,
page=page,
**kwargs
)
You could do this, but why would you want to? Django has a simple, well-defined and well-documented way of passing data into templates - through the context. Why try and find ways to work around that?
Edit after comment No. Again, Django has a perfectly good way of passing extra context into a generic view, via the extra_context parameter which again is well-documented.
You're not showing the actual function you use to render your view (render(), render_to_response(), etc.).
Let's say you are using render_to_response() :
render_to_response(template_name[, dictionary][, context_instance][, mimetype])
Renders a given template with a given
context dictionary and returns an
HttpResponse object with that rendered
text.
So if you pass in {"foo": your_object} as a dictionary you can use {{ foo }} directly in your template.
If you are using the object_list generic view you should use the extra_context:
extra_context: A dictionary of values
to add to the template context. By
default, this is an empty dictionary.
If a value in the dictionary is
callable, the generic view will call
it just before rendering the template.