For loop counter in Django, numbers not showing up - python

I'm looking to have a counter of numbers from one to ten using a for loop counter in Django, but I don't see any numbers. I don't really understand what I need to put in {{counter}} and {{value}} when looking at the documentation.
List.html
<p class="number">
{% for key, value in data.items %}
{{counter}}: {{value}}
{% endfor %}
<p>
models.py
from django.db import models
from django.core.urlresolvers import reverse
# Create your models here.
class FullArticleQuerySet(models.QuerySet):
def published(self):
return self.filter(publish=True)
class FullArticle(models.Model):
title = models.CharField(max_length=150)
author = models.CharField(max_length=150)
slug = models.SlugField(max_length=200, unique=True)
pubDate = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
category = models.CharField(max_length=150)
heroImage = models.CharField(max_length=250, blank=True)
relatedImage = models.CharField(max_length=250, blank=True)
body = models.TextField()
publish = models.BooleanField(default=True)
gameRank = models.CharField(max_length=150, blank=True, null=True)
objects = FullArticleQuerySet.as_manager()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("FullArticle_detailed", kwargs={"slug": self.slug})
class Meta:
verbose_name = "Blog entry"
verbose_name_plural = "Blog Entries"
ordering = ["-pubDate"]
views.py
from django.views import generic
from . import models
from .models import FullArticle
# Create your views here.
class BlogIndex(generic.ListView):
queryset = models.FullArticle.objects.published()
template_name = "list.html"
randomArticle = FullArticle.objects.order_by('?').first()
class BlogDetail(generic.DetailView):
model = models.FullArticle
template_name = "detailed.html"

use {{ forloop.counter }} instead of just {{ counter }}
Also, you are never defining the dictionary data anywhere. What is this supposed to be? Your queryset?

Related

How can I show a many-to-many field values in a form?

i wrote a code about music and used Many-To-Many-Field() as genre but when i try to show genres it just shows : Genre['a number']
template:
{% extends 'pages/base.html' %}
{% block content %}
<form>
{% if mdata.image %}
<img src="mdata.image.url" height="500" width="500">
{% endif %}
{% for field in form %}
<p>{{ field.label }} : {{ field.value}}</p>
}
{% endfor %}
</form>
edit
{% endblock %}
models is here:(i didnt know which one u need so pasted both of them)
from django.db import models
from django.contrib.auth.models import User
class Genre(models.Model):
name = models.CharField(unique=True,max_length=20)
def __str__(self):
return self.name.title()
class Mdata(models.Model):
name = models.CharField(max_length=100)
artist = models.CharField(max_length=150)
album = models.CharField(max_length=100)
nation = models.CharField(max_length=100)
duration = models.DecimalField(max_digits=4,decimal_places=2)
released_in = models.DecimalField(max_digits=4,decimal_places=0)
uploaded_at = models.DateTimeField(auto_now_add=True)
image = models.ImageField(upload_to='images/',blank=True,null=True)
audio = models.FileField(upload_to='audios/',null=True,blank=True)
genre = models.ManyToManyField(Genre)
uploader = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return self.name.title()+" by "+self.artist.title()
forms.py:(its just a simple form im using)
[![class MdataForm(ModelForm):
class Meta:
model = Mdata
fields =\[
'name',
'artist',
'album',
'genre',
'nation',
'duration',
'released_in',
'image',
'audio',
]
and here the render :dunno if this is enough
[1]: https://i.stack.imgur.com/T5eK2.png
This could be that you don't have a __str__ method on your Genre model. Add a __str__ method and return the genre name. That would be something like:
def __str__(self):
return self.name
self.name here being the field on your genre model used to specify the name. In the sample image below, I set the custom user to return the username by default, that way anywhere I call a user it will automatically show the name of the genre.
class CustomUser(AbstractUser):
id = models.UUIDField(primary_key=True, editable=False, default=uuid4)
email = models.EmailField(_("email address"), unique=True, null=True)
phone_number = PhoneNumberField(unique=True, null=True)
username = models.CharField(max_length=100, unique=True, null=True)
password = models.CharField(_("password"), max_length=128, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = "User"
verbose_name_plural = "Users"
def __str__(self):
return self.username

How do I create a queue of records in django?

In general, when I experimented with the capabilities of Django, I had a question how I can add a queue for model records, for example, I have a couple of blocks and I need to display the model that was registered first and on the second block it should be displayed next entry. How can I do this?
here is an example query_set
class IndexView(generic.ListView):
template_name = 'article/sale.html'
model = Goods
context_object_name = 'goods'
def get_queryset(self):
return Goods.objects.order_by('-pub_date')[:1]
In html, I output the entry like this
{% for good in queryset %}
<h1 class="price" >{{ good.price2_text }}</h1>
{% endfor %}
this is code of models.py
class Goods(models.Model):
description_text = models.CharField(max_length=200)
price_text = models.CharField(max_length=200)
image_sale = models.ImageField(blank=True, upload_to='images/')
description1_text = models.CharField(max_length=200)
price1_text = models.CharField(max_length=200)
image1_sale = models.ImageField(blank=True, upload_to='images/')
description2_text = models.CharField(max_length=200)
price2_text = models.CharField(max_length=200)
image2_sale = models.ImageField(blank=True, upload_to='images/')
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.description_text
def __str__(self):
return self.price_text
def __str__(self):
return self.description1_text
def __str__(self):
return self.price1_text
def __str__(self):
return self.description2_text

how to split post view on the same page in django

I have no idea if this question make much sense or not but i am so confused about it. I have a post list view and it is rendering some of the post here.
My question is how can I split the sections of the page.something like this.
what should be the approach of making this kind of view.
this is my posts view.py
posts/view.py
class PostListView(ListView):
model = Post
template_name = 'posts/home.html'
context_object_name = 'posts'
ordering = ['-date_posted']
def get_queryset(self):
if not self.request.user.is_authenticated:
return Post.objects.all()[:10]
else :
return super().get_queryset()
posts/models.py
from django.db import models
from django.utils import timezone
from slugger import AutoSlugField
from django.contrib.auth.models import User
from django.urls import reverse
# Create your models here.
def upload_location(instance, filename):
return "%s/%s" %(instance.slug, filename)
class Category(models.Model):
title = models.CharField(max_length= 60)
slug = AutoSlugField(populate_from='title')
parent = models.ForeignKey('self',blank=True, null=True ,related_name='children',on_delete=models.CASCADE)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
def __unicode__(self):
return self.title
def __str__(self):
return self.title
class Post(models.Model):
title = models.CharField(max_length=120)
slug = AutoSlugField(populate_from='title')
image = models.ImageField(
upload_to=upload_location,
null=True,
blank=True,
)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self, slug=None):
return reverse("posts-detail", kwargs={"slug": self.slug})
You have posts assigned to categories. Each post could be assigned only to one category (since you have FK from Post to Category). And you want to display all categories and 10 latest posts under each one.
I see several ways of how to solve that. The easiest one is to extend Category model with property, containing the queryset to retrieve related posts in the way you want them for front page.
class Post(models.Model):
title = models.CharField(max_length=255)
category = models.ForeignKey('Category', on_delete=models.CASCADE, related_name='posts')
date_posted = models.DateTimeField(default=timezone.now)
class Category(models.Model):
title = models.CharField(max_length=255)
#property
def posts_for_frontpage(self):
return self.posts.order_by('-date_posted')[:10]
class FrontpageView(ListView):
model = Category
template_name = 'frontpage.html'
context_object_name = 'categories'
def get_queryset(self):
# select some categories for frontpage
# all by default
return Category.objects.all()
and then in template
{% for category in categories %}
<h1>{{ category.title }}</h1>
<hr />
{% for post in category.posts_for_frontpage %}
<h4>{{ post.title }}</h4>
{% endfor %}
<br />
<br />
{% endfor %}
You could also play with select_related to reduce number of queries and with annotate to get all related posts.

Need to know the way to access to my Reply table?

Here is my models.py py file.
from django.db import models
from django.conf import settings
from django.urls import reverse
class Article(models.Model):
'''Modelling the article section.'''
title = models.CharField(max_length=200)
body = models.TextField()
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
'''Return string representation of the model.'''
return self.title
def get_absolute_url(self):
'''Return the url of this model.'''
return reverse('article_detail', args=[str(self.id)])
class Comment(models.Model):
'''Modelling the comment section.'''
article = models.ForeignKey(
Article,
on_delete = models.CASCADE,
related_name = 'comments'
)
comment = models.CharField(max_length=150)
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
def __str__(self):
'''String representation of the model. '''
return self.comment
class Reply(models.Model):
''' Modelling the reply section. '''
comment = models.ForeignKey(
Comment,
on_delete = models.CASCADE,
related_name = 'replys'
)
reply = models.CharField(max_length=100)
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
def __str__(self):
''' String representation of the model. '''
return self.reply
I need to access my Reply table in the Detail View template(Using generic view class DetailView). I have tried so far the following command in the template.
article.comments.replys.all
Its not able to retrive any data from Reply table. Thanks in advance.
article.comments is a manager; you need to iterate over it to get Comment instances. Each one will have .replys.
{% for comment in article.comments.all %}
{% for reply in comment.replys.all %}
...
{% endfor %}
{% endfor %}

Template filter for generating product by category

I have a django project where I am displaying products in the template. What is the best possible way of displaying the product by category using some sort of template filter. For instance, on the template if I want to display Breads by category Hovis. At the moment all the products in the database will be displayed.
<tr>
<td><h5>{{ product.name }}</h5></td>
<td><p><strong>{{ product.price }}</strong></p></td>
</tr>
Copy of Models.py (as requested):
from django.db import models
from django.core.urlresolvers import reverse
class Category(models.Model):
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True, unique=True)
class Meta:
ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
# def get_absolute_url(self):
# return reverse('shop:product_list_by_category', args=[self.slug])
class Product(models.Model):
category = models.ForeignKey(Category, related_name='products')
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('-created',)
index_together = (('id', 'slug'),)
def __str__(self):
return self.name
# def get_absolute_url(self):
I would send the already prepared data from the view to the template to avoid additional logic in the front-end. You could do something like this in the view:
products = Product.objects.all()
all_products_by_cat ={}
for product in products:
if all_products_by_cat.get(product.category):
all_products_by_cat[product.category].append(product)
else:
all_products_by_cat[product.category] = [product]
And in the template you would just do:
{% for product in all_products_by_cat['some_category'] %}
<!-- do something with the product-->
{% endfor %}

Categories

Resources