I want to display number of comments on blog home page where all post is showing up. I want to show number of comments on little comment icon under every post is having.
Models:
class BlogPost(models.Model):
sno = models.AutoField(primary_key=True)
title = models.CharField(max_length=60, null=False, blank=False)
body = models.TextField(max_length=5000, null=False, blank=False)
image = models.ImageField(upload_to=upload_location, null=False, blank=True)
date_published = models.DateTimeField(auto_now_add=True, verbose_name="date_published")
date_updated = models.DateTimeField(auto_now=True, verbose_name="date_updated")
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
category = models.CharField(max_length=20, choices=CATEGORIES_NAME, default='Entertainment')
slug = models.SlugField(blank=True, unique=True)
def __str__(self):
return self.title
class BlogComment(models.Model):
sno = models.AutoField(primary_key=True)
comment = models.TextField()
user = models.ForeignKey(Account, on_delete=models.CASCADE)
post = models.ForeignKey(BlogPost, on_delete=models.CASCADE)
timestamp = models.DateTimeField(default=now)
def __str__(self):
return str(self.sno)
Homepage view:
BLOG_POSTS_PER_PAGE = 4
def home_screen_view(request):
context = {}
query = ""
if request.GET:
query = request.GET.get('q', '')
context['query'] = str(query)
blog_posts = sorted(get_blog_queryset(query), key=attrgetter('date_updated'), reverse=True)
comments = BlogComment.objects.all()
# Pagination
page = request.GET.get('page', 1)
blog_posts_paginator = Paginator(blog_posts, BLOG_POSTS_PER_PAGE)
try:
blog_posts =blog_posts_paginator.page(page)
except PageNotAnInteger:
blog_posts =blog_posts_paginator.page(BLOG_POSTS_PER_PAGE)
except EmptyPage:
blog_posts =blog_posts_paginator.page(blog_posts_paginator.num_pages)
context['blog_posts'] = blog_posts
context['comments'] = comments
return render(request, "personal/home.html", context)
Related
I have created a e-commerce project. I have 3 models. Item, CartItem, Placeorder(checkout). I am looping through user's cart which has multiple items so that I can get each item and make a placeorder instance. But the for loop works only for the first time and when I try to placeorder(checkout) again with multiple items, the old data(records) are deleted and replaced by new data in the for loop. I do not understand this behavior. I cannot get past this. Maybe I am making some silly mistake.
models.py
SUB_CATEGORY_CHOICES = (
('Veg','Veg'),
('Non-Veg','Non-Veg'),
)
QUANTITY_CHOICES = (
('Half','Half'),
('Full','Full')
)
class Item(models.Model):
name =models.CharField(max_length=1000)
description =models.CharField(max_length=2000)
# snacks, maincourse, soups, rice, ice-cream
category =models.CharField(max_length=1000)
# veg, non-veg
# sub_category =models.CharField(max_length=1000,blank=True,null=True)
sub_category =models.CharField(choices=SUB_CATEGORY_CHOICES, max_length=1000)
images1 =models.FileField(upload_to='food_image',blank=True,null=True)
images2 =models.FileField(upload_to='food_image',blank=True,null=True)
price =models.CharField(max_length=500)
add_date =models.DateTimeField(default=timezone.now)
# half, full
quantity_size =models.CharField(choices=QUANTITY_CHOICES,max_length=1000, blank=True,null=True)
avg_rating =models.FloatField(default='0',blank=True,null=True)
def __str__(self):
return '%s - %s - %s' % (self.id,self.name,self.price)
class Meta:
ordering = ['-add_date']
class CartItem(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
the_item = models.ForeignKey(Item, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
price = models.IntegerField()
def __str__(self):
return '%s - %s' % (self.the_item.name, self.the_item.sub_category)
class Placeorder(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
order_items = models.ForeignKey(CartItem, on_delete=models.CASCADE)
item_quantity = models.IntegerField(default=1)
first_name = models.CharField(max_length=200, null=True)
last_name = models.CharField(max_length=200, null=True)
shipping_phone_number = models.IntegerField(null=True)
shipping_address_1 = models.CharField(max_length=500, null=True)
shipping_address_2 = models.CharField(max_length=500, null=True)
shipping_city = models.CharField(max_length=200, null=True)
shipping_district = models.CharField(max_length=200, null=True)
shipping_state = models.CharField(max_length=200, null=True)
shipping_zipcode = models.IntegerField(null=True)
billing_phone_number = models.IntegerField(null=True)
billing_address_1 = models.CharField(max_length=500, null=True)
billing_address_2 = models.CharField(max_length=500, null=True)
billing_city = models.CharField(max_length=200, null=True)
billing_district = models.CharField(max_length=200, null=True)
billing_state = models.CharField(max_length=200, null=True)
billing_zipcode = models.IntegerField(null=True)
payment_mode = models.CharField(default='', max_length=100,null=False,blank=False)
date_added = models.DateTimeField(default=timezone.now)
delivered = models.BooleanField(default=False)
customer_delivered = models.BooleanField(default=False)
def __str__(self):
return f'{self.user.username} -- {self.order_items.the_item}'
views.py
def checkout_page(request):
items = CartItem.objects.filter(user=request.user)
cart_total = CartItem.objects.filter(user=request.user).aggregate(Sum('price'))
context = {
'cart_total': cart_total['price__sum'],
'items':items,
'total_items':len(items),
}
return render(request, 'resto/newcheckout.html', context)
def checkout_action(request):
items = CartItem.objects.filter(user=request.user)
if request.method == 'POST':
shipping_phone_number = request.POST.get('shipping_phone_number')
shipping_address_1 = request.POST.get('shipping_address_1')
shipping_address_2 = request.POST.get('shipping_address_2')
shipping_city = request.POST.get('shipping_city')
shipping_district = request.POST.get('shipping_district')
shipping_state = request.POST.get('shipping_state')
shipping_zipcode = request.POST.get('shipping_zipcode')
billing_phone_number = request.POST.get('billing_phone_number')
billing_address_1 = request.POST.get('billing_address_1')
billing_address_2 = request.POST.get('billing_address_2')
billing_city = request.POST.get('billing_city')
billing_district = request.POST.get('billing_district')
billing_state = request.POST.get('billing_state')
billing_zipcode = request.POST.get('billing_zipcode')
payment_mode = request.POST.get('COD')
same_billing_address = request.POST.get('same_billing_address')
for item in items:
checkout_item = CartItem.objects.get(id=item.id)
print('item.pk: ', item.pk)
checkout_instance = Placeorder(
user=request.user,
order_items=item,
item_quantity=item.quantity,
first_name=request.user.first_name,
last_name=request.user.last_name,
shipping_phone_number=shipping_phone_number,
shipping_address_1=shipping_address_1,
shipping_address_2=shipping_address_2,
shipping_city=shipping_city,
shipping_district=shipping_district,
shipping_state=shipping_state,
shipping_zipcode=shipping_zipcode,
)
checkout_instance.save()
return HttpResponseRedirect(reverse('myorders'))
I gues your return HttpResponseRedirect(reverse('myorders')) should has less indent, otherwise you get return after first iteration of loop
def checkout_action(request):
items = CartItem.objects.filter(user=request.user)
if request.method == 'POST':
...
for item in items:
...
return HttpResponseRedirect(reverse('myorders'))
My models:
class ClientProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, related_name='client_profile')
follows = models.ManyToManyField(User,
related_name='follows',blank=True)
profile_picture = models.ImageField( blank=True)
phone_regex = RegexValidator(
regex=r'^\+?1?\d{9,15}$',
message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed."
)
mobile_number = models.CharField(validators=[phone_regex],
max_length=17, blank=True)
dob = models.DateField(auto_now = False, null = True)
profile_summary = models.TextField()
my_career_objective = models.TextField()
educational_qualification = models.CharField(max_length=200)
work_experience = models.IntegerField(blank=True, null=True)
skill_set = models.TextField(blank=True)
address_1 = models.CharField(max_length=300,blank=True)
address_2 = models.CharField(max_length=300,blank=True)
# new fileds
about_me = models.TextField(blank=True)
birthplace = models.CharField(max_length=150,blank=True)
lives_in = models.CharField(max_length=150,blank=True)
occupation = models.CharField(max_length=150, blank=True)
gender = models.CharField(choices=GENDER_CHOICES,max_length=150, blank=True)
marital_status = models.CharField(choices=MARITAL_CHOICES,max_length=150, blank=True,default=1)
religion = models.CharField(max_length=150, blank=True)
political_incline = models.TextField(blank=True)
# other_social_networks = models.TextField(blank=True)
hobbies = models.TextField(blank=True)
favorite_tv_shows = models.TextField(blank=True)
favorite_movies = models.TextField(blank=True)
favorite_games = models.TextField(blank=True)
favorite_music_band_artists = models.TextField("Favorite Music, Bands / Artists", blank=True)
favorite_books = models.TextField(blank=True)
favorite_writers = models.TextField(blank=True)
other_interests = models.TextField(blank=True)
subscription = models.TextField(blank=True, null=True, default="Free")
def __str__(self):
return str(self.user.first_name) + " " + str(self.user.last_name)
class Task(models.Model):
level = models.ForeignKey(Level, on_delete=models.CASCADE)
todo = models.ForeignKey(ToDo, on_delete=models.CASCADE)
student = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=150)
content = models.TextField()
timestamp = models.TimeField(auto_now=True)
datestamp = models.DateField( auto_now=True)
like = models.ManyToManyField(User,related_name='user_likes',blank=True)
is_verified=models.BooleanField(default=False,blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('student:dashboard')
objects = PostManager()
#property
def comments(self):
instance = self
qs = Comment.objects.filter_by_instance(instance)
return qs
#property
def get_content_type(self):
instance = self
content_type =
ContentType.objects.get_for_model(instance.__class__)
return content_type
I want to display all tasks from logged in user and also all the tasks from all users followed by logged in user.What is the best django query to implement this? the follows field in the ClientProfile model is given as many to many field to depict all users followed by the user.How to write django query with 'or'.Each task points to a user through foreign key 'student' . I want to display all tasks from logged in user and all users followed by logged in user in the homepage
Put a related_name attribute in student field of Task. (let's call it task)
If logged_in_user is your logged in user object then logged_in_user.task would give task of logged_in_user and for user's followers tasks:
tasks = Task.objects.filter(student__in= logged_in_user.follows.all())
Without related_name.
task = Task.objects.filter(Q(student=logged_in_user) | Q(student__in=logged_in_user.follows.all()))
This worked for me :
client=ClientProfile.objects.get(user=request.user)
task = Task.objects.filter
(Q(student=request.user) |
Q(student__in=client.follows.all()))
.order_by('timestamp').prefetch_related('images_set')
I have a many to many relationship in my product model (category field). I am able to display the category data in a select box which is a multiple selection. What I want to do is have the user select one or more categories from the template and then save the data in my product model. Here is my code:
if request.method =='POST':
print ('entered')
name = request.POST['name']
brand = request.POST['brand']
sku = request.POST['sku']
price = request.POST['price']
quantity = request.POST['quantity']
description = request.POST['description']
imageurls = request.POST['urls']
print('imageurls',imageurls)
categorylist = request.POST['categories']
print('categorylist',categorylist)
categories = re.findall(r"[\w']+", categorylist)
print categories
imageurls = imageurls.split('~')
print('iageurls',imageurls)
for x in categories:
categoryobj = Category.objects.filter(name=x).values()
_id = categoryobj.id
print('_id',_id)
print ('categoryobj',categoryobj)
# Product.objects.create(name=name,sku=sku,brand=brand,price=price,quantity=quantity,description=description,imageurls=imageurls,categories=categoryobj)
return HttpResponse('success')
models.py
class Category(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, unique=True,
help_text='Unique value for product page URL, created from name.')
description = models.TextField()
is_active = models.BooleanField(default=True)
meta_keywords = models.CharField("Meta Keywords", max_length=255,
help_text='Comma-delimited set of SEO keywords for meta tag')
meta_description = models.CharField("Meta Description", max_length=255,
help_text='Content for description meta tag')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('catalog:categories', kwargs={'category_slug': self.slug})
class Meta:
ordering = ['-created_at']
verbose_name_plural = 'Categories'
class Product(models.Model):
name = models.CharField(max_length=255, unique=True)
slug = models.SlugField(max_length=255, unique=True,
help_text='Unique value for product page URL, created from name.')
brand = models.CharField(max_length=50)
sku = models.CharField(max_length=50)
price = models.DecimalField(max_digits=9, decimal_places=2)
old_price = models.DecimalField(max_digits=9, decimal_places=2, blank=True, default=0.00)
thumbnail = models.FileField(upload_to='static/images/products/thumbnails')
imageurls = models.CharField(max_length=1000)
is_active = models.BooleanField(default=True)
is_bestseller = models.BooleanField(default=False)
is_featured = models.BooleanField(default=False)
quantity = models.IntegerField()
description = models.TextField()
meta_keywords = models.CharField(max_length=255, help_text='Comma-delimited set of SEO keywords for meta tag')
meta_description = models.CharField(max_length=255, help_text='Content for description meta tag')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
categories = models.ManyToManyField(Category)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('catalog:products', kwargs={'product_slug': self.slug})
def sale_price(self):
if self.old_price > self.price:
return self.price
else:
return None
class Meta:
ordering = ['-created_at']
You should use Django ModelForms. So you only need to check if form.is_valid() and then do form.save().
Save method authomatically creates a new object for you.
Let me know if this works!
My problem is have two models job and company and i want to get all jobs in this company
My urls.py:
url(r'^jobs/(?P<slug>[\w-]+)/$', views.job_at_company, name='job_at_company'),
My views.py:
def job_at_company(request, slug):
return render(request, 'jobs.html')
My models.py:
class Company(models.Model):
title = models.CharField(max_length=100, blank=False)
slug = models.SlugField(blank=True, default='')
city = models.CharField(max_length=100, blank=False)
contact_info = models.CharField(max_length=100, blank=False, default=0)
facebook = models.CharField(max_length=100, blank=True)
twitter = models.CharField(max_length=100, blank=True)
linkedin = models.CharField(max_length=100, blank=True)
logo = models.ImageField(upload_to="logo", default=0)
class Jobs(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(blank=True, default='')
company = models.ForeignKey(Company, on_delete=models.CASCADE)
price = models.IntegerField(default='')
Description = models.TextField(blank=True, null=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
job_type = models.CharField(max_length=100, choices=(('Full Time', 'Full Time'),('Part Time', 'Part Time')),default='Full Time')
in the views.py we can add this
def job_at_company(request, slug):
results = Jobs.objects.filter(company__slug=slug)
context = {'items':results}
return render(request, 'jobs.html',context)
Suppose you pass id in the url. The id is the primary key of the company. You would have to modify your url to accept id like -
url(r'^jobs/(?P<slug>[\w-]+)/(?P<pk>[\d]+)$', views.job_at_company, name='job_at_company')
And modify your views.py -
def job_at_company(request, slug, pk):
jobs_qs = Jobs.objects.filter(company__id=pk)
return render(request, 'jobs.html', {'jobs': jobs_qs})
And use it in your html like -
{% for job in jobs %}
{{job.title}}
{% endfor %}
Look at this link. Django's documentation is helpful, follow that
I'm creating a page that has one video , as many comments , replies for each comment
I could retrieve video and comments but replies for each comment haven't been retrieved eventually.
I made some for loops in views file but didn't know also how to retrieve it in the templates file.
I'm stuck between views and templates till now
I'm using django 1.10.4
models.py
class Video(models.Model):
title = models.CharField(max_length=120)
embed_code = models.CharField(max_length=500)
slug = models.SlugField(null=True, blank=True)
category = models.ForeignKey("Category", null=True)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
active = models.BooleanField(default=True)
featured = models.BooleanField(default=False)
free_preview = models.BooleanField(default=False)
share_message = models.CharField(max_length=150, default=default_share_message)
objects = models.Manager()
# activemodel = ActiveModel()
featuresandactive = Features()
class Meta:
unique_together = ('slug', 'category')
def __str__(self):
return self.title
def get_absolute_url(self):
try:
return reverse('video_detail', kwargs={'vid_slug':self.slug, 'cat_slug':self.category.slug})
except:
return "/"
class Comment(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(MyUser)
path = models.CharField(max_length=350)
video = models.ForeignKey(Video, null=True, blank=True)
text = models.TextField()
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
Timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
active = models.BooleanField(default=True)
objects = CommentManager()
def __str__(self):
return self.text
class Reply(models.Model):
user = models.ForeignKey(MyUser)
comment = models.ForeignKey(Comment,null=True, blank=True)
text = models.TextField()
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
Timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
active = models.BooleanField(default=True)
objects = ReplyManager()
def __str__(self):
return self.text
views.py
def video_detail(request, cat_slug, vid_slug):
cat = Category.objects.get(slug=cat_slug)
comments = Comment.objects.filter(video=obj)
replys = Reply.objects.filter(comment=comments)
context = {
"cat": cat,
"obj":obj,
"comments":comments,
"replys":replys,
}
return render(request, 'video_detail.html', context)
this is another view.py
I tried this also but didn't work
def video_detail(request, cat_slug, vid_slug):
cat = Category.objects.get(slug=cat_slug)
obj = Video.objects.get(slug=vid_slug)
comments = obj.comment_set.all()
Replies = Reply.objects.filter(comment_id=comments.id))
context = {
"cat": cat,
"obj":obj,
"comments":comments,
"replies":replies
}
return render(request, 'video_detail.html', context)
IMO, you can represent the comments in your template. your template may look like this.
# your_template.html
{% for comment in obj.comment_set.all %}
{{comment.user}}: {{comment.text}}
{% for reply in comment.reply_set.all %}
{{reply.user}}: {{reply.text}}
{% endfor %}
{% endfor %}
then your view function only needs cat and obj, not comments or replies. also check out select_related.