I have the following blog project :
urls.py conf :
url(r'^author/(?P<author>\w+)/$', views.getAllPosts, name='grabAuthorPosts')
posts/models:
class Post(models.Model):
title = models.CharField(max_length=200)
summary = models.CharField(max_length=500, default = True)
body = models.TextField()
pub_date = models.DateTimeField(default=timezone.now)
category = models.ManyToManyField('Category')
author = models.ForeignKey(User, default=True)
slug = models.SlugField(max_length=100, unique=True, blank=True)
def __str__(self):
return self.title
def slug(self):
return slugify(self.title)
posts/views:
def getAllPosts(request, author=False):
latest_posts = Post.objects.all().order_by('-pub_date')
comments = Comment.objects.all().order_by('-pub_date')
author_posts = User.objects.get(id=author)
author_posts = author_posts.post_set.all()
context = {
'latest_posts':latest_posts,
'comments':comments,
'author_posts':author_posts
}
return render(request, 'posts/getAllPosts.html', context)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
templates/posts/getAllPosts:
<a href={% url 'grabAuthorPosts' author=post.author.username %}>
{{post.author}}</a>
I am trying to make it so that when the post.author link is clicked, the user will be taken to a page consisting of posts related to that particular author. The link formulation itself seems ok, as when clicked on a post created by admin, the url reads localhost/author/admin/
I believe my problem is in getting the context variable author_posts to work. I'm new to Django so any explanation greatly appreciated.
latest_posts, as well as author=False is used elsewhere in the template to get all posts regardless of author, which works fine.
The error is :
ValueError at /author/admin/
invalid literal for int() with base 10: 'admin'
Related
i'm starting out with Django and trying to render all Shows(screenings) that selected Movie had. Here's the code:
url
path('movie/<int:pk>/', MovieDetails.as_view(), name='movie'),
Models
class Movie(models.Model):
title = models.CharField(max_length=200)
description = models.CharField(max_length=255, blank=True)
def __str__(self):
return f'{self.title}'
class Show(models.Model):
show_date = models.DateField()
start_time = models.TimeField()
movie = models.ForeignKey(Movie, on_delete=models.CASCADE, null=True, blank=True)
city = models.ForeignKey(City, on_delete=models.CASCADE, null=True, blank=True)
title = models.CharField(max_length=200, blank=True)
def __str__(self):
return f'{self.show_date}'
View
class MovieDetails(DetailView):
model = Movie
context_object_name = 'movie'
def get_queryset(self):
self.movie = get_object_or_404(Movie, id=self.kwargs['pk']) #find movie by id from url
shows_played = Show.objects.filter(movie=self.movie)
print(shows_played) #prints out some shows
return shows_played
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['shows_played'] = Show.objects.filter(movie=self.movie)
return context
The shows_played prints out some shows, so it seems like everything is fine but when the url: /movies/1
is called I get a 404, No show found matching the query rendered in browser and
Not Found: /movie/1/ printed in console
What am i doing wrong?
Thank you
I figured it out. My mistake was that i was using DetailView instead of ListView(which has get_queryset method) for "MovieDetails".
I'm using Django Fabulous to create a tagging system for a project I'm working on. I want to display posts that have tags similar to the users' skills in their profile. Any solution or suggestion is greatly appreciated!
The error I get is 'TagDescriptor' object is not iterable which I think is related to JobPosts\views.py.
JobPosts\models.py (Works fine)
class Skill(tagulous.models.TagTreeModel):
class TagMeta:
initial = [
'Python/Django',
'Python/Flask',
'JavaScript/JQuery',
'JavaScript/Angular.js',
'Linux/nginx',
'Linux/uwsgi',
]
space_delimiter = False
force_lowercase = True
max_count = 5
protected = True
class JobPost(models.Model):
user = models.ForeignKey(User, default=1, null=True, on_delete=models.CASCADE)
title = models.CharField(max_length=120, unique=False)
slug = models.SlugField(unique=True, blank=True)
content = models.TextField(null=True, blank=True)
jobskill = tagulous.models.TagField(Skill)
JobPosts/views.py (This is where I need help)
def job_post_list_view(request):
if request.user.is_authenticated and request.user.is_superuser:
my_qs = JobPost.objects.filter(user=request.user)
elif request.user.is_authenticated:
my_qs = JobPost.objects.filter(Q(user=request.user) | Q(jobskill__in=User.userskill))
template_name = 'home.html'
context = {
'job_list': my_qs
}
return render(request, template_name, context)
JobPosts\urls.py
urlpatterns = [
path('browse/', views.job_post_list_view, name='job_post_list'),
]
home.html
{% for object in job_list %}
{% include 'jobpost/post.html' with job_post=object truncate=True detail=False %}
{% endfor %}
UserManager\models.py
from JobPosts.models import Skill
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=254, unique=True)
u_name = models.CharField(max_length=254, null=True)
userskill = tagulous.models.TagField(Skill, blank=True)
full_name = models.CharField(max_length=254, null=True, blank=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
You have Q(jobskill__in=User.userskill which says "of all the JobPost objects, find the ones where the jobskill is one of the userskill attribute of the User model"
You need to change that to "is one of the userskills of the user I'm interested in":
Q(jobskill__in=request.user.userskill
I'm trying to link to a blog post but it has a slug in it, and i'm not sure how to pass it in. I've looked online but I didn't apparently understand the answers since I haven't found a solution yet.
I'm trying to do like the following in my template href="{% url 'blog_detail' post.categories.5 slug=blender-task-name post.14 %}", but it gives me the following exception: Could not parse the remainder: '-task-name' from 'blender-task-name'
post.categories.5 because i'm trying to access category with id 5
and post.14 because it's the post with the id 14
This is how the object i'm trying to link to looks like
URLS.py:
urlpatterns = [
path("", views.blog_index, name="blog_index"),
path("<category>/<slug>/<int:pk>/", views.blog_detail, name="blog_detail"),
path('<category>/', views.blog_category, name='blog_category'),
]
Models.py:
class Category(models.Model):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class Post(models.Model):
slug = models.SlugField(max_length = 250, null = True, blank = True)
title = models.CharField(max_length = 250, default="Blog Post")
body = models.TextField()
created_on = models.DateTimeField(null=True)
last_modified = models.DateTimeField(null=True)
categories = models.ForeignKey('Category', related_name='posts', default="2", unique=False, on_delete=models.CASCADE)
class Comment(models.Model):
author = models.CharField(max_length=60)
body = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
post = models.ForeignKey('Post', on_delete=models.CASCADE)
Quick question - I'm not sure what would be the correct way to handle this. Essentially I wish to define a custom tag which handles some logic then returns all posts of model Post which has the is_featured field set to True. I have tried a number of avenues to get this working, but none have worked. My last coherant "guess" was the following:
templatetags/blog_tags.py:
#register.inclusion_tag('blog/post/featured_posts.html')
def show_featured_posts(count=4):
"""Return 4 of the most recent posts (of model: 'Post') that has the variable is_featured set to True."""
if Post.is_featured:
featured_posts = Post.published.order_by('-publish')[:count]
return { 'featured_posts': featured_posts}
models.py (useful bits):
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager, self).get_queryset().filter(status='published')
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
POST_TYPES = (
('news', 'News'),
('feature', 'Feature'),
('review', 'Review'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique_for_date='publish')
author = models.ForeignKey(UserProfile, related_name='blog_posts')
body = models.TextField()
lead_in = models.CharField(max_length=500, default='')
#These next items shall contain our development information for game reviews - this is much like the lead_in:
platform = models.CharField(max_length=1000, default='')
publisher = models.CharField(max_length=1000, default='')
developer = models.CharField(max_length=1000, default='')
release = models.DateTimeField(default=timezone.now)
is_featured = models.BooleanField(default=False)
#Out blog layout dictates each featurette has up to three scrolling images associated to it:
image_scroll_1 = models.ImageField(storage=site_media_upload_location, null=True, blank=True)
image_scroll_2 = models.ImageField(storage=site_media_upload_location, null=True, blank=True)
image_scroll_3 = models.ImageField(storage=site_media_upload_location, null=True, blank=True)
type = models.CharField(max_length=10,choices=POST_TYPES,default='review')
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10,choices=STATUS_CHOICES,default='draft')
rating = models.PositiveSmallIntegerField(default=10)
wrap_header = models.CharField(max_length=250, default='')
wrap_up = models.TextField(default='')
disclaimer = models.TextField(default='')
objects = models.Manager()
published = PublishedManager()
tags = TaggableManager()
class Meta:
ordering = ('-publish',)
def __str__(self):
"""Return the state title of the post"""
return self.title
def get_absolute_url(self):
"""Get absolute_url path specific to this post."""
return reverse('blog:post_detail', args = [self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug])
def get_image(self):
"""Get upload_to path specific to this photo."""
return self.image.url
That is everything I think I need to include - I have the featured_posts.html template all ready to go so I don't think the issue lies with that. It's purely in the blog_tags.py file.
replace the following code in blog_tags.py
if Post.is_featured:
featured_posts = Post.published.order_by('-publish')[:count]
to
featured_posts = Post.published.filter(is_featured=True).order_by('-publish')[:count]
I am having a trouble understanding what is wrong inside my code. Please can anybody tell me why the fields in locations = Location.objects.filter(user=add_profile.user) are not displayed in my html page.
models.py
class Location(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
my_location = models.CharField(max_length=120, choices=LOCATION_CHOICES)
update_date = models.DateField(auto_now=True, null=True)
date = models.DateField()
def __str__(self):
return self.my_location
class UserProfile(models.Model):
user = models.OneToOneField(User)
user_base = models.CharField(max_length=120, choices=LOCATION_CHOICES)
user_position = models.CharField(max_length=120)
user_phone = models.CharField(max_length=50)
first_name = models.CharField(max_length=120, null=True)
last_name = models.CharField(max_length=120, null=True)
slug = models.SlugField()
def save(self, *args, **kwargs):
self.slug = slugify(self.user)
super(UserProfile, self).save(*args, **kwargs)
def __unicode__(self):
return self.user.username
views.py
#login_required
def details(request, user_slug):
add_profile = UserProfile.objects.get(slug=user_slug)
locations = Location.objects.filter(user=add_profile.user)
print(locations)
context = {'add_profile': add_profile, locations: "locations"}
return render(request, 'details.html', context)
Though, the print(locations) is printing the requested data inside my cmd.
html code
{% for l in locations %}
<ul>
<li> {{l.my_location}} </li>
</ul>
{% endfor %}
My problem is that I am not having any an error to do know where to look.
Thank you.
Instead of
context = {'add_profile': add_profile, locations: "locations"}
should be
context = {'add_profile': add_profile, 'locations': locations}
Instead of using locations as value for context, you've used it as key and as value just the string "locations".