Notification template only printing out items after the 3rd position. When I inspect element to check if its showing up in the frontend, its there, but its just a blank html <p> tag. Other than this minor bug it works fine. Not sure how to proceed, any help is much appreciated.
Here are my models.py
class Notification(models.Model):
MESSAGE = 'message'
APPLICATION = 'application'
CHOICES = (
(MESSAGE, 'Message'),
(APPLICATION, 'Application')
)
to_user = models.ForeignKey(User, related_name='notifications', on_delete=models.CASCADE)
notification_type = models.CharField(max_length=20, choices=CHOICES)
is_read = models.BooleanField(default=False)
extra_id = models.IntegerField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey(User, related_name='creatednotifications', on_delete=models.CASCADE)
class Meta:
ordering = ['-created_at']
notification views.py
#login_required
def notifications(request):
goto = request.GET.get('goto', '')
notification_id = request.GET.get('notification', 0)
extra_id = request.GET.get('extra_id', 0)
if goto != '':
notification = Notification.objects.get(pk=notification_id)
notification.is_read = True
notification.save()
if notification.notification_type == Notification.MESSAGE:
return redirect('room', pk=notification.extra_id)
elif notification.notification_type == Notification.APPLICATION:
return redirect('room', pk=notification.extra_id)
return render(request, 'notification/notifications.html')
notifications.html template
{% extends 'main.html' %}
{% block content %}
<div class="container">
<h1 class="title">Notifications</h1>
{% if not notifications %}
No notifications yet!
{% endif %}
{% for notification in notifications %}
<div class="notification">
<p>
{% if notification.notification_type == 'message' %}
<a href="{% url 'notifications' %}?goto=room¬ification={{ notification.id }}&extra_id={{ notification.extra_id }}">
<strong>{{ notification.created_by.username }}</strong> sent you a message<br>
<small>{{ notification.created_at|timesince }} ago</small>
</a>
{% elif notification.notification_type == 'application' %}
<a href="{% url 'notifications' %}?goto=room¬ification={{ notification.id }}&extra_id={{ notification.extra_id }}">
<strong>{{ notification.created_by.username }}</strong> created a room<br>
<small>{{ notification.created_at|timesince }} ago</small>
</a>
{% endif %}
</p>
</div>
{% endfor %}
</div>
{% endblock %}
The notifications that only print an empty <P> probably don't have a notification_type that equals 'message' or 'application'.
Related
I have to do wishlist, I have done wishlist page, model and html.bBut when I click on the button bellow my post, I'm redirected to wishlist page and post didnt saved in my wishlist.So thats my code:
models.py
class Wishlist(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
wished_item = models.ForeignKey(Posts, on_delete=models.CASCADE)
def __str__(self):
return self.wished_item.title
class Posts(models.Model):
TYPE = Choices(
('private', _('private')),
('business', _('business')),
)
STATUS = Choices(
('active', _('active')),
('deactivated', _('deactivated'))
)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='posts',
on_delete=models.CASCADE, verbose_name='owner')
phone_number = PhoneNumberField(verbose_name=_('Phone_number'), null=False, blank=False, unique=True)
title = models.CharField(verbose_name=_('Title'), max_length=100)
text = RichTextField(verbose_name=_('Text'))
image = models.ImageField(upload_to='images/%Y/%m/%d/', null=True, blank=True, validators=[file_size])
price = models.DecimalField(verbose_name=_('Price'), decimal_places=2, max_digits=9)
status = models.CharField(choices=STATUS, max_length=50)
created = models.DateTimeField(auto_now=True)
type = models.CharField(choices=TYPE, max_length=50)
def __str__(self):
return self.title
views.py
class WishListView(generic.View):
def get(self, *args, **kwargs):
wish_items = Wishlist.objects.filter(user=self.request.user)
context = {
'wish_items': wish_items
}
return render(self.request, 'wishlist/wishlist.html', context=context)
def addToWishList(request):
if request.method == 'POST':
post_var_id = request.POST.get('object-id')
post_var = Posts.objects.get(id=post_var_id)
print(post_var)
try:
wish_item = Wishlist.objects.get(user=request.user, post=post_var)
if wish_item:
wish_item.save()
except:
Wishlist.objects.create(user=request.user, post=post_var)
finally:
return HttpResponseRedirect(reverse('wishlist'))
wishlist.html
{% extends 'posts/base.html' %}
{% load thumbnail %}
{% block content %}
<div>
{% for item in wish_items %}
{% if item.wished_item.image1 %}
<img src="{{item.wished_item.image.url}}" alt="">
{% endif %}
</div>
<div>
<li>{{item.wished_item.title}}</li>
<li>{{item.wished_item.text}}</li>
<li>{{item.wished_item.price}}</li>
<li>{{item.wished_item.phone_number}}</li>
{% if item.wished_item.image %}
<img src="{% thumbnail item.wished_item.image 200x200 crop %}" alt="" />
<p></p>
{% endif %}
</div>
{% endfor %}
{% endblock %}
urls.py
urlpatterns = [
path("wishlist/", WishListView.as_view(), name='wishlist'),
path("add-to-wishlist", addToWishList, name='add-to-wishlist'),
]
and all posts template with add to wishlist button.
<ul>
{% for object in object_list %}
<li>Owner: {{ object.owner }}</li>
<li>Phone: {{ object.phone_number }}</li>
<li>Title: {{ object.title }}</li>
<li>Text: {{ object.text }}</li>
<li>Type: {{ object.type }}</li>
<li>Price: {{ object.price }}</li>
<li>Date: {{ object.created }}</li>
<p>
{% if object.image %}
<img src="{% thumbnail object.image 200x200 crop %}" alt="" />
{% endif %}
</p>
<form action="{% url 'add-to-wishlist' %}" method="POST">
{%csrf_token%}
<input type="hidden" name="object-id" value="{{object.id}}">
<input type="submit" value="Add to Wishlist">
</form>
<hr/>
Probably problem with posts Id, but I'm not sure in that.
You can use get_or_create instead of the if else statement for if exist or not. And use get_object_or_404 to make code more clear.
from django.shortcuts import get_object_or_404
def addToWishList(request):
if request.method == 'POST':
post_obj = get_object_or_404(Post, pk=request.POST.get('object-id'))
Wishlist.objects.get_or_create(user=request.user, post=post_obj)
return HttpResponseRedirect(reverse('wishlist'))
In your views.py try to replace these lines:
try:
wish_item = Wishlist.objects.get(user=request.user, post=post_var)
if wish_item:
wish_item.save()
except:
Wishlist.objects.create(user=request.user, post=post_var)
with
wish_item, was_created = Wishlist.objects.get_or_create(user=request.user, post=post_var)
# for debugging
if was_created:
print(f"{wish_item} was created")
else:
print(f"{wish_item} already exists")
what is the output?
The code looks OK for me. You might add a trailing / in your urls.py after the path("add-to-wishlist/" ... but I can't spot anything wrong in the first place.
So I got a QuerySet result from an aggregate function to display in a low-spec eBay clone of mine. But my problem is displaying certain fields in the Django template as I want, for example, I want to display the highest bidder's username and bid. When I call the whole object itself like so {{winner}}, then it displays. But when I try to access its fields like so {{winner.user_id.username}}, I get no output although the QuerySet does execute.
When I try to get a field like so (winner.user_id.username):
When I only call winner:
models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
CATEGORIES = [
('Appliances', 'Appliances'),
('Tech', 'Tech'),
('Gaming', 'Gaming'),
('Fashion', 'Fashion'),
('Sports and Fitness','Sports and Fitness'),
('Other','Other'),
("Hygiene and Medicine","Hygiene and Medicine"),
("Stationery","Stationery"),
('Decor', 'Decor'),
('Furniture','Furniture'),
('Cars and Mechanical Things','Cars and Mechanical Things'),
("Tools","Tools")
]
# Create models here
class User(AbstractUser):
pass
class Auction_Listing(models.Model):
user_id = models.IntegerField(default=1)
list_title = models.CharField(max_length=64)
desc = models.TextField(max_length=600)
img_url = models.URLField(max_length=200, null=True, blank=True)
start_bid = models.IntegerField()
category = models.CharField(choices=CATEGORIES, max_length=35, null=True, blank=True)
active = models.BooleanField(default=True)
def __str__(self):
return f"ID:{self.id}, {self.list_title}: {self.desc}, {self.start_bid} posted by user:{self.user_id} in Category:{self.category}, url:{self.img_url}"
class Bids(models.Model):
user_id = models.ForeignKey('User', on_delete=models.CASCADE)
auctions = models.ForeignKey('Auction_Listing', on_delete=models.CASCADE, default=1,related_name='bidauc')
bid = models.IntegerField()
def __str__(self):
return f"ID:{self.id}, Bid {self.bid} posted by user:{self.user_id} on auction {self.auctions}"
class Auction_Comments(models.Model):
user_id = models.ForeignKey('User', on_delete=models.CASCADE)
comment = models.TextField(max_length=324, default='N/A')
auctions = models.ForeignKey('Auction_Listing', on_delete=models.CASCADE, default=1,related_name='comauc')
def __str__(self):
return f"ID:{self.id}, Comment: {self.comment} posted by user:{self.user_id} on auction {self.auctions}"
class Watchlist(models.Model):
user_id = models.ForeignKey('User', on_delete=models.CASCADE)
auctions = models.ForeignKey('Auction_Listing', on_delete=models.CASCADE, default=1, related_name='watchauc')
def __str__(self):
return f"ID:{self.id}, user:{self.user_id} on auction {self.auctions}"
views.py
def render_listing(request, title):
if request.method == "POST":
form = BidForm(request.POST)
bid = int(request.POST['new_bid'])
listing = Auction_Listing.objects.get(list_title=title)
comments = Auction_Comments.objects.filter(auctions=listing)
if bid <= listing.start_bid:
error = True
else:
error = False
listing.start_bid = bid
listing.save()
new_bid = Bids(user_id=request.user, auctions=listing, bid=bid)
new_bid.save()
return render(request, 'auctions/listing.html', {
"listing": listing,
"form": form,
"comments": comments,
"error": error,
"comform": CommentForm()
})
else:
form = BidForm()
comform = CommentForm()
listing = Auction_Listing.objects.get(list_title=title)
comments = Auction_Comments.objects.filter(auctions=listing)
high_bid = Bids.objects.filter(auctions=listing).aggregate(maximum=Max("bid"))
winner = Bids.objects.filter(auctions=listing, bid=high_bid['maximum'])
print(winner)
return render(request, 'auctions/listing.html', {
"listing": listing,
"form": form,
"comments": comments,
"error": False,
"comform": comform,
"winner": winner
})
template's code:
{% extends "auctions/layout.html" %}
{% load static %}
{% block title %} Listing: {{listing.list_title}} {% endblock %}
{% block body %}
{% if listing.active %}
<h2>{{ listing.list_title }}</h2>
<div class='listing'>
{% if listing.img_url == "" or listing.img_url == None %}
<a href='#'><img src="{% static 'auctions/img404.png' %}" class='img-fluid'></a>
{% else %}
<a href='#'><img src="{{ listing.img_url }}" class="img-fluid" alt='image of {{ listing.list_title }}'></a>
{% endif %}
<p>
{{ listing.desc }}
</p>
<p>
Current Bid: ${{ listing.start_bid }}
</p>
<p>Category: {{ listing.category }}</p>
<p></p>
{% if user.is_authenticated %}
<div class="bid">
<a href='{% url "watch" listing.list_title %}' class='btn btn-primary'>Add to/Remove from Watchlist</a>
{% if listing.user_id == user.id %}
<a href='{% url "close" listing.list_title %}' class='btn btn-primary'>Close Auction</a>
{% endif %}
</div>
<div class="bid">
<h3>Bid:</h3>
<form method="POST" action='{% url "renlist" listing.list_title %}'>
{% csrf_token %}
{{form}}
<button type="submit" class='btn btn-primary'>Make New Bid</button>
{% if error %}
Please enter a bid higher than the current bid.
{% endif %}
</form>
</div>
{% else %}
<p><a href='{% url "register" %}' class='register'>Register</a> to bid on this item and gain access to other features</p>
{% endif %}
</div>
<div class="listing">
<h3>Comments:</h3>
{% if user.is_authenticated %}
<div id='comform'>
<h4>Post a Comment</h4>
<form method="POST" action="{% url 'commentadd' %}">
{% csrf_token %}
{{comform}}
<button type="submit" class="btn btn-primary">Post Comment</a>
</form>
</div>
{% endif %}
<p>
{% for comment in comments %}
<div class="comment">
<h4>{{comment.user_id.username}} posted:</h4>
<p>{{comment.comment}}</p>
</div>
{% empty %}
<h4>No comments as of yet</h4>
{% endfor %}
</p>
</div>
{% else %}
<h2>This auction has been closed</h2>
<div>
<a href='{% url "watch" listing.list_title %}' class='btn btn-primary'>Add to/Remove from Watchlist</a>
</div>
<p>{{winner.user_id.username}}</p>
{% endif %}
{% endblock %}
Thanks in advance for the help!
Kind Regards
PrimeBeat
This will give a QuerySet. You can see in your second image.
A QuerySet represents a collection of objects from your database.
winner = Bids.objects.filter(auctions=listing, bid=high_bid['maximum'])
You need to iterate over that QuerySet, get whatever data you want and show it in your template.
{% for win in winner %}
<p>{{ win.user_id.username }}</p>
{% endfor %}
I know there are a bunch of questions addressing this issue, but I haven't solved it out yet. please any help i tried many solutions but didn't work
models.py
class Board(models.Model):
name = models.CharField(max_length=50,unique=True)
description = models.CharField(max_length=150)
def __str__(self):
return self.name
class Topic(models.Model):
subject = models.CharField(max_length=255)
board = models.ForeignKey(Board,related_name='topics',on_delete=models.CASCADE)
created_by = models.ForeignKey(User,related_name='topics',on_delete=models.CASCADE)
created_dt = models.DateTimeField(auto_now_add=True)
class Post(models.Model):
message = models.TextField(max_length=4000)
topic = models.ForeignKey(Topic, related_name='posts',on_delete=models.CASCADE)
created_by = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE)
created_dt = models.DateTimeField(auto_now_add=True)
view.py
def new_topic(request,board_id):
board = get_object_or_404(Board,pk=board_id)
if request.method == 'POST':
subject = request.POST['subject']
message = request.POST['message']
user = User.objects.first()
topic = Topic.objects.create(
subject=subject,
board=board_id,
created_by=user
)
post = Post.objects.create(
message=message,
topic=topic,
created_by=user
)
new_topic.html
{% extends 'base.html' %}
{% block title %}Start a New Topic{% endblock %}
{% block breadcrumb %}
<li class="breadcrumb-item">Boards</li>
<li class="breadcrumb-item">{{ board.name }}</li>
<li class="breadcrumb-item active">New topic</li>
{% endblock %}
{% block content %}
<form method="post">
{% csrf_token %}
<div class="form-group">
<label for="id_subject">Subject</label>
<input type="text" class="form-control" id="id_subject" name="subject">
</div>
<div class="form-group">
<label for="id_message">Message</label>
<textarea class="form-control" id="id_message" name="message" rows="5"></textarea>
</div>
<button type="submit" class="btn btn-success">Add</button>
</form>
{% endblock %}
I'm fairly new to Django. How would I go about resolving that?
in new_topic(views.py), convert board=board_id to board=board
I'm new to Django and I'ma building a basic blog application.
I cant show manytomany field (in tags) and a foreignkey field (comments) in my details page.
models.py
class BlogContent(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=200)
content = models.TextField()
date_published = models.DateField(auto_now=True)
image = models.ImageField(upload_to='media/')
def __str__(self):
return self.title
class TagName(models.Model):
tag = models.ManyToManyField(BlogContent, null=True)
name = models.CharField(max_length=100, blank=True, null=True)
def __str__(self):
return self.name
class Comment(models.Model):
comt_text = models.TextField()
comments = models.ForeignKey(BlogContent, on_delete=models.CASCADE)
date_published = models.DateField(auto_now=True)
name = models.CharField(max_length=200, blank=True, null=True)
def __str__(self):
return self.name
views.py
def details(request, blogcontent_id):
data_blog = get_object_or_404(BlogContent, pk=blogcontent_id)
data_tag = get_object_or_404(TagName, pk=blogcontent_id)
data_comment = Comment.objects.select_related()
return render(request, 'details.html',
{'data_blog': data_blog, 'data_tag':data_tag, 'data_comment':data_comment})
details.html
{% extends 'base.html' %}
{% block body_base %}
<img class="card-img-top img-responsive" src={{ data_blog.image.url }} alt="Card image cap">
<h2 class="blog-post-title">{{ data_blog.title }}</h2>
<p class="blog-post-meta">{{ data_blog.date_published }} {{ data_blog.author }}</p>
<p>{{ data_blog.content }}</p>
{% endblock %}
how do i show foreignkey and manaytomany fieds after this?
TBH this is much easier if you use class based views.
The view would simply be:
class BlogContentDetail (DetailView):
model = BlogContent
The url call would be url(r'^blog-detail/(?P<pk>\d+)/$, BlogContentDetail.as_view(), name="blog_detail")
Your html file should be called blogcontent_detail.html and held within the app subfolder in the templates folder
The template would then be:
{% extends 'base.html' %}
{% block body_base %}
<img class="card-img-top img-responsive" src={{ object.image.url }} alt="Card image cap">
<h2 class="blog-post-title">{{ object.title }}</h2>
<p class="blog-post-meta">{{ object.date_published }} {{ object.author }}</p>
<p>{{ object.content }}</p>
{% for tag in object.tags_set.all %}{{ tag }}{% endfor %}
{% endblock %}
You can iterate the ManyToMany Field in this way
{% for tags in data_tag.tag.all %}
<p > {{tags}} </ p>
{% endfor %}
For foreign key
{{data_comment.comments}}
Wagtail Blog Site - Comment Model Form Issues
I'm creating a blog site, using Wagtail, and I've run in to a snag. I've added a Comment Model to my page, which I can add comments through the admin section and they display on the correct posts, but the comment form I've created is not displaying for some reason. Here's my relevant code. Any tips on where I went wrong would be greatly appreciated.
blog/models.py
class BlogPage(Page):
date = models.DateField("Post date")
intro = models.CharField(max_length=250)
body = RichTextField(blank=True)
#tag manager
tags = ClusterTaggableManager(through=BlogPageTag, blank=True)
#get feature image
def main_image(self):
gallery_item = self.gallery_images.first()
if gallery_item:
return gallery_item.image
else:
return None
search_fields = Page.search_fields + [
index.SearchField('intro'),
index.SearchField('body'),
]
content_panels = Page.content_panels + [
MultiFieldPanel([
FieldPanel('date'),
FieldPanel('tags'),
], heading="Blog information"),
FieldPanel('intro'),
FieldPanel('body'),
InlinePanel('gallery_images', label="Gallery images"),
]
def serve(self, request):
# Get current page
post = self
# Get comment form
form = CommentForm(request.POST or None)
# Check for valid form
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect(request.path)
return render_to_response(self,
{
'post': post,
'form': form,
},
context_instance=RequestContext(request))
class Comment(models.Model):
post = models.ForeignKey(BlogPage, related_name='comments')
author = models.CharField(max_length=250)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
approved_comment = models.BooleanField(default=False)
def approve(self):
self.approved_comment = True
self.save()
def __unicode__(self):
return self.text
def __str__(self):
return self.text
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('author', 'text',)
blog_page.html
{% extends "base.html" %}
{% load wagtailcore_tags wagtailimages_tags %}
{% block body_class %}template-blogpage{% endblock %}
{% block content %}
<div class="section">
<div class="container">
<h1 class="title">{{ page.title }}</h1>
<p class="meta subtitle">{{ page.date }}</p>
{% with page.main_image as main_image %}
{% if main_image %}{% image main_image fill-500x300 %}{% endif %}
{% endwith %}
<p>{{ main_image.caption }}</p>
<div class="hero-body subtitle">{{ page.intro }}</div>
<div class="content">
{{ page.body|richtext }}
{% if page.tags.all.count %}
<div class="tags">
<h3>Tags</h3>
{% for tag in page.tags.all %}
<span class="tag is-primary is-medium is-link"><a style="color: white" href="{% slugurl 'tags' %}?tag={{ tag }}">{{ tag }}</a></span>
{% endfor %}
</div>
{% endif %}
<p>Return to blog archive</p>
<hr>
<br>
<form action="" method="POST">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input class="control button is-primary" type='submit' name='submit' value='Add Comment'>
</form>
<br>
<hr>
<div class="section">
{% if page.comments.all.count %}
<h2 class='subtitle'>Comments</h2>
<div class="comments">
{% for comment in page.comments.all %}
{% if comment.approved_comment %}
<div class="comment">
<h5 class="date">{{ comment.created_date }}</h5>
<strong><h3 class="title is-3">{{ comment.author }}</h3></strong>
<h4 class="subtitle is-5">{{ comment.text|linebreaks }}</h4>
<br>
<hr>
</div>
{% endif %}
{% empty %}
<br>
<p>No comments yet...</p>
{% endfor %}
</div>
{% endif %}
</div>
</div>
</div>
</div>
{% endblock %}
Now I'm getting an error saying:
File "/home/kenneth/development/web/sites/mysite/dynamicsalesops/blog/models.py", line 88, in serve
context_instance=RequestContext(request))
TypeError: render_to_response() got an unexpected keyword argument 'context_instance'
Your view_post function is never used. In Wagtail, rendering pages as HTML is handled by a serve method on the page model itself, not by a separate view function: http://docs.wagtail.io/en/v1.9/reference/pages/theory.html#anatomy-of-a-wagtail-request