Django Admin Panel can't access specific items - python

I've got a model of an article and everything works fine except when I change their status to draft - it disappears from Admin Django Panel. New articles are successfully added, but then don't show, the admin panel just can't access them. When I change the URL to force the admin panel to show me the details so I could edit it, I get a message that the article with the given ID doesn't exist. So basically every draft article gets lost. But I know they have to exist in my database because they show up on my article list view, but I can't go to detail view or draft view as I always get "No NewsModel matches the given query"
Django 2.0.5
models.py
class NewsModel(models.Model):
STATUS_CHOICES = (
('draft','Draft'),
('published','Published'),
)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
title = models.CharField(max_length=250)
slug = AutoSlugField(populate_from='title')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=10, choices=STATUS_CHOICES)
image = models.ImageField(upload_to="news/")
description = models.TextField(null=True, blank=True)
def get_absolute_url(self):
from django.urls import reverse
return reverse('main:news_details', kwargs={'slug':self.slug})
def __str__(self):
return self.title
class Meta:
ordering = ('-publish',)
verbose_name = 'News'
verbose_name_plural = 'News'
admin.py
#admin.register(NewsModel)
class NewsAdmin(admin.ModelAdmin):
list_display = ('title', 'game', 'news_type', 'author', 'finish', 'publish')
views.py
def news_details(request, slug):
news = get_object_or_404(NewsModel, slug=slug)
news_aside = NewsModel.objects.filter(game=news.game).exclude(id=news.id)[:5]
return render(request, 'news/news_details.html', {'news':news, 'news_aside':news_aside, 'section':'news'})
def news(request):
""" List of all news """
news = NewsModel.objects.filter(status='published')[:3]
latest = news[0]
second = news[1]
third = news[2]
all_kind_news = NewsModel.objects.all()
return render(request, 'news/news.html', {'news':news, 'section':'news', 'all':all_kind_news, 'latest':latest, 'second':second, 'third':third, 'section':'news'})
def drafts(request):
""" List of all drafts """
news = NewsModel.objects.filter(status='draft')
paginator = Paginator(news, 9)
page = request.GET.get('page')
try:
news = paginator.page(page)
except PageNotAnInteger:
news = paginator.page(1)
except EmptyPage:
news = paginator.page(paginator.num_pages)
return render(request, 'news/news_list.html', {'news':news, 'section':'news', 'page':page})
urls.py (attaching just in case)
path('news/', views.news, name='news'),
path('news/<slug>', views.news_details, name='news_details'),
path('news/drafts', views.drafts, name='drafts'),
News_details, drafts, and admin panel throw 404 error while trying to access drafts, but the news list doesn't have that problem. The weirdest thing is that also admin panel is affected.

Related

How do i query model managers in my function based views for single_page(detail.html)

I'm finding it difficult to query a custom django model manager in my function based detail view. How can i resolve this?
I'm using django 2.2.
in my models.py file, i have this code below, which works perfectly. Querying for the listview is working fine and when i query the detail view using get_object_or_404(Modelname, id), the detail views works too but when i try to query it using my custom model manager, i keep getting this error
"movie_detail() got an unexpected keyword argument 'id'".
i've also tried removing--->
def get_absolute_url(self):
return reverse('core:movie_detail', args=[self.id,])
from my movie model when querying the model manager, but am still get same error
How can i resolve this?
my models.py
class MovieManager(models.Manager):
def all_with_related_persons(self):
qs = self.get_queryset()
qs = qs.select_related('director')
qs = qs.prefetch_related('writers', 'actors')
return qs
class Movie(models.Model):
NOT_RATED = 0
RATED_G = 1
RATED_PG = 2
RATED_R = 3
RATINGS = (
(NOT_RATED, 'NR - Not Rated'),
(RATED_G, 'G - General Audiences'),
(RATED_PG, ' PG - Parental Guidance' 'Suggested'),
(RATED_R, 'R - Restricted'),
)
title = models.CharField(max_length=140)
plot = models.TextField()
year = models.PositiveIntegerField()
rating = models.IntegerField(choices=RATINGS, default=NOT_RATED)
runtime = models.PositiveIntegerField()
website = models.URLField(blank=True)
director = models.ForeignKey(to='Person',
on_delete=models.SET_NULL,
related_name="directed",
null=True,
blank=True)
writer = models.ManyToManyField(to="Person", related_name="writing_credits", blank=True)
actors = models.ManyToManyField(to="Person", through="Role", related_name="acting_credits", blank=True)
objects = MovieManager()
def __str__(self):
return '{} ({})'.format(self.title, self.year)
def get_absolute_url(self):
return reverse('core:movie_detail', args=[self.id,])
class Meta:
ordering = ('-year', 'title',)
<--- Views.py --->
My List view
def movie_list(request):
object_list = Movie.objects.all()
paginator = Paginator(object_list, 12)
page_number = request.GET.get('page', 1)
try:
page = paginator.page(page_number)
except PageNotAnInteger:
# If page is not an integer deliver the first page
page = paginator.page(1)
except EmptyPage:
# If page is out of range deliver last page of results
page = paginator.page(paginator.num_pages)
context = {
'object_list': object_list,
'products': page,
'page': page,
}
template = 'core/movie_list.html'
return render(request, template, context)
DetailView without custom model manager.(This works)
def movie_detail(request, id):
object_list = get_object_or_404(Person, id=id)
context = {'movie': object_list}
template = 'core/person_detail.html'
return render(request, template, context)
DetailView with custom model manager.(This doesn't work. throws an error "movie_detail() got an unexpected keyword argument 'id'")
def movie_detail(request):
object_list = Movie.objects.all_with_related_persons()
context = {'movie': object_list}
template = 'core/movie_detail.html'
return render(request, template, context)
My url path to the detail_view
path('<id>/', views.movie_detail, name="movie_detail"),
I expect detail view to return queries based on what i queried in my custom model manager.
Your url pattern for the movie_detail view is passing an id kwarg to your view, so your view needs to accept this id as argument. Instead of
def movie_detail(request)
you should define
def movie_detail(request, id)
The error you see just says: movie_detail was called with keyword argument id, meaning it was called like this: movie_detail(request=the_request, id=some_id) which can't work if it's defined to only have one argument, request.
But also, since you're making a detail view for one object, you should probably do something with the id to select the specific object:
def movie_detail(request, id):
object_list = Movie.objects.all_with_related_persons()
try:
movie = object_list.get(id=id)
except Movie.DoesNotExist:
raise Http404
context = {'movie': movie}
template = 'core/movie_detail.html'
return render(request, template, context)

How to arrange search results by the date they were created on?

I made a search bar but it gives the queries in an old to new order i want to change that to a new to old. I want to see the recent matches for my search first then the more old ones.
views.py
search_term=''
if 'search' in request.GET:
search_term_extract = request.GET['search']
search_term = Blog.objects.filter(Q(title__icontains=search_term_extract)|Q(author__username__icontains=search_term_extract))
paginator = Paginator(search_term, 8)
page = request.GET.get('page')
paginator_page = paginator.get_page(page)
results=search_term.all()['-date_posted']
message=True
nav=False
and models.py
class Blog(models.Model):
title=models.CharField(max_length=100)
content=models.TextField(blank=True)
date_posted=models.DateTimeField(default=timezone.now)
author=models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
Use .order_by() on your queryset:
search_term = Blog.objects.filter(Q(title__icontains=search_term_extract)|
Q(author__username__icontains=search_term_extract)).order_by("-date_posted")

Django query to get all formset images belonging to a particular object via foreign key relationship

views.py
def TrainerDashView(request):
if not request.user.is_authenticated:
return redirect('accounts:index')
else:
page = request.GET.get('page', 1)
notifications = Notification.objects.filter(receiver= request.user,task__is_verified=False)
count = Notification.objects.filter(receiver = request.user).count()
tasks = Task.objects.filter(student__mentor=request.user,is_verified=False)
paginator = Paginator(tasks,1)
try:
tasklist = paginator.page(page)
except PageNotAnInteger:
tasklist = paginator.page(1)
except EmptyPage:
tasklist = paginator.page(paginator.num_pages)
context={
'notifications':notifications,
'trainer':request.user,
'tasks': tasklist,
}
return render(request,'mentor.html',context)
models.py
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:task-detail', kwargs={'pk': self.pk})
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
class Images(models.Model):
post = models.ForeignKey(Task, default=None,on_delete=models.CASCADE)
image = models.ImageField(verbose_name='Image')
Im using formsets to connect 3 images to a particular task.I want to display the 3 images for the task in template.The tasks are displayed as a list with pagination ,1 task per page. How do i get all the 3 images and display for a particular task? Confused about the query to use !
pagee = request.GET.get('page')
if pagee == None:
pagess=1
else:
pagess=int(pagee)
print("PAGE NUMBER",pagess)
try:
images = Images.objects.filter(post=tasks[pagess-1])
except KeyError:
raise TypeError('Index error')
I found a solution .By getting the current page number i could give it as the index of the tasks array and get the images correctly !

Display latest "commentator" username in forum app [Django]

I am creating a forum app, and want to display latest commentator's username(as seen in screenshot):
But I have some gaps in information, here is my code so far:
Models
class Forum(models.Model):
"""
Forum Model
"""
forum_author = models.ForeignKey(
Profile,
related_name='user_forums',
null=True,
blank=True,
on_delete=models.CASCADE
)
forum_title = models.CharField(
max_length=225,
verbose_name=u'Thread Title',
blank=False,
null=False
)
forum_category = models.ForeignKey(
'Category',
verbose_name=u'Thread Category',
)
forum_content = MarkdownxField()
class Comment(models.Model):
"""
Comment Model
"""
forum = models.ForeignKey(
'Forum',
related_name='forum_comments'
)
comment_author = models.ForeignKey(
Profile,
related_name='user_comments',
null=True,
blank=True,
on_delete=models.CASCADE
)
comment_content = MarkdownxField()
created_date = models.DateTimeField(
default=datetime.datetime.now,
)
Forum list views - display all threads
...
from app_forum.models import Forum, Comment
def forum_list_view(request):
forum_list = Forum.objects.all().order_by("-misc_created")
return render(request, 'app_forum/forum_list.html' {'forum_list': forum_list})
My single thread views :
def forum_single_view(request, pk):
forum = get_object_or_404(Forum, pk=pk)
forum_comments = Comment.objects.filter(forum=forum.id)
paginator = Paginator(forum_comments, 10)
page = request.GET.get('page', 1)
try:
forum_comments = paginator.page(page)
except PageNotAnInteger:
forum_comments = paginator.page(1)
except EmptyPage:
forum_comments = paginator.page(paginator.num_pages)
return render(request, 'app_forum/forum_single.html', {'forum': forum, 'forum_comments': forum_comments})
You can get the latest comment by
L_comment = Comment.objects.latest('created_date')
You can get the commented user by
L_comment.comment_author
If you want to get the latest comment in a particular forum then,
forum = Forum.objects.get(forum_title='forum-title')
latest_comment = forum.forum_comments.latest('created_date')
author = latest_comment.comment_author
Updates:
Much better option is to define a method in your Forum Class, like this:
def latest_comment_author(self):
return self.forum_comments.latest('created_at').comment_author
And you can access it from the template by
{{ forum.latest_comment_author }}
You can use the related object manager for this. Create a method on your Forum model to retrieve the latest comment on the forum. Something like:
#cached_property
def latest_coment(self):
return self.forum_comments.order_by('-created_date').first()
Then you can call this method on your template to get the latest comment on it

Need help creating a model in a view

models.py
class Match(models.Model):
match_name = models.CharField(max_length=100)
player = models.CharField(max_length=100, choices=match_game, default=2)
time_start = models.DateTimeField(blank=True, default=None, null=True)
match_finished = models.BooleanField(default=False)
def get_absolute_url(self):
return reverse('match:details', kwargs={'pk': self.pk})
def __str__(self):
return self.match_name
class PlayerSignup(models.Model):
current_player = models.ForeignKey(User)
signup = models.ForeignKey(Match)
urls.py
url(r'^create/add/$', views.MatchCreate.as_view(), name='match-add'),
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(template_name = 'match/bracket_detail.html'), name='details'),
url(r'^search/$', views.IndexView.as_view(template_name = 'match/bracket.html'), name='search'),
url(r'(?P<pk>[0-9]+)/$', views.PlayerSign, name='join')
views.py
def PlayerSign(request):
model = PlayerSignup.objects.all()
match = Match.objects.get(pk=Match.pk)
joinmatch = PlayerSignup(current_player=request.user, signup=match)
joinmatch.save()
return render(request, 'match/bracket_detail.html', {'model': model })
template
Join Match
when a person clicks on the 'Join Match' link i would like it to create a PlayerSignup model and link it to the current match that they are on.
when i click the Join Match link nothing happens, no new model, no error
First, try to edit this statement
def PlayerSign(request):
...
match = Match.objects.get(pk=Match.pk)
to
def PlayerSign(request, pk):
...
match = Match.objects.get(pk=pk)
Because there is an request parameter in URL named pk, you should pass this parameter to the query method.
Second, review your url define
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(template_name = 'match/bracket_detail.html'), name='details'),
url(r'(?P<pk>[0-9]+)/$', views.PlayerSign, name='join')
Change to
url(r'^match_detail/(?P<pk>[0-9]+)/$', views.DetailView.as_view(template_name = 'match/bracket_detail.html'), name='details'),
url(r'^player_detail/(?P<pk>[0-9]+)/$', views.PlayerSign, name='join')

Categories