I'm new Django and have been working on project. When I click on my techposts. it says No Techpost matches the given query. It was working fine and I didn't change anything. Not sure what could have happened. It has happened 2-3 times. Database flush used to fix this issue. But now nothing is working. Please suggest how do I fix this and the possible reason behind this?
PS: Found similar questions but their answers didnt help.
CODE:
models.py
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager, self).get_queryset().filter(status='published')
class Techpost(models.Model):
STATUS_CHOICS=(
('draft', 'Draft'),
('published', 'Published')
)
title = models.CharField(max_length=255, blank=False, null=False)
slug = models.SlugField(max_length=255, unique_for_date='publish')
author = models.ForeignKey(User, on_delete=models.CASCADE,
related_name='tech_posts')
body = models.TextField()
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_CHOICS, default='draft')
tags = TaggableManager()
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
objects = models.Manager() # default manager
published = PublishedManager() # Custom Manager.
def get_absolute_url(self):
return reverse('rincon:techpost_details', args=[
self.publish.year,
self.publish.strftime('%m'),
self.publish.strftime('%d'),
self.slug
])
class Comment(models.Model):
techpost = models.ForeignKey(Techpost, on_delete=models.CASCADE,
related_name='comments')
comment = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now =True)
active = models.BooleanField(default=True)
class Meta:
ordering = ('created',)
def __str__(self):
return "Comment on {}".format(self.techpost)
views.py
#login_required
def techpost_details(request, year, month, day, techpost):
techpost = get_object_or_404(Techpost, slug=techpost, status='published',
publish__year=year, publish__month=month, publish__day=day)
comments = techpost.comments.filter(active=True)
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.techpost = techpost
new_comment.save()
comment_form = CommentForm()
else:
comment_form = CommentForm()
techpost_tags_ids = techpost.tags.values_list('id', flat=True)
similar_techposts = Techpost.published.filter(tags__in=techpost_tags_ids)\
.exclude(id=techpost.id)
similar_techposts = similar_techposts.annotate(same_tags=Count('tags'))\
.order_by('-same_tags', '-publish')[:4]
return render(request, 'rincon/details.html', {'techpost': techpost, 'comments': comments, 'comment_form': comment_form, 'similar_techposts': similar_techposts})
urls.py
app_name = 'rincon'
urlpatterns =[
path('', views.home, name='home'),
path('submit/', views.request_submit, name='request_submit'),
path('techposts/', views.techpost_list, name='techpost_list'),
path('tag/<slug:tag_slug>/', views.techpost_list, name='techpost_list_by_tag'),
path('<slug:techpost_id>/share/', views.techpost_share, name='techpost_share'),
path('search/', views.techpost_search, name='techpost_search'),
path('hotfixes/', views.hotfixes, name='hotfixes'),
path('autocomplete/', views.autocomplete, name='autocomplete'),
path('<int:year>/<int:month>/<int:day>/<slug:techpost>/', views.techpost_details, name='techpost_details'),
Related
I get an Error:
cannot unpack non-iterable bool object
profile = Profile.objects.get(Profile.user == request.user)
This is my models.py in account app and blog app:
class Profile(models.Model):
STATUS_CHOICES = (
('manager', 'مدیر'),
('developer', 'توسعهدهنده'),
('designer', 'طراح پروژه'),
)
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
bio = models.CharField(max_length=50, blank=True)
task = models.CharField(choices=STATUS_CHOICES, max_length=20, blank=True, null=True, default=None)
date_of_birth = models.DateField(blank=True, null=True)
photo = models.ImageField(upload_to='users/photos/%Y/%m/%d/', blank=True)
def __str__(self):
return f'{self.user.get_full_name()}'
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='user_comments')
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
active = models.BooleanField(default=False)
and this is my views.py for comments:
def post_detail(request, year, month, day, slug):
post = get_object_or_404(Post, slug=slug, status='published', publish__year=year, publish__month=month, publish__day=day)
tags = Tag.objects.all()
tagsList = []
for tag in post.tags.get_queryset():
tagsList.append(tag.name)
profile = Profile.objects.get(Profile.user == request.user)
comments = post.comments.filter(active=True)
new_comment = None
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.profile = profile
new_comment.post = post
new_comment.save()
return redirect('post_detail', slug=post.slug)
else:
comment_form = CommentForm()
post_tags_ids = post.tags.values_list('id', flat=True)
similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id)
similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags', '-publish')[:3]
return render(request, 'blog/post/detail.html', {'post': post, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form, 'similar_posts': similar_posts, 'tagsList': tagsList, 'tags': tags})
Is there any solution for this problem?
Assuming you need to get only single profile instance i.e. current logged in user's profile so you can either use:
profile = Profile.objects.get(user=request.user)
or:
get_object_or_404(Profile, user=request.user)
To limit the view to be accessed by only logged in users, use #login_required decorator so:
#login_required(login_url='/accounts/login/') # you can give any login_url you want.
def post_detail(request, year, month, day, slug):
#...
When i try to create an new post with http://localhost:8000/create/ , i get this error. I couldn't find the solution thought they seem similar. I follows some blog tutorial
I can't paste the settings.py here because there to much code in the post but i think the settings.py is fine btw
My models.py (* i deleted some code maynot involve)
User = get_user_model()
class Author(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_picture = models.ImageField()
def __str__(self):
return self.user.username
class Post(models.Model):
title = models.CharField(max_length=100)
overview = models.TextField()
detail = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
content = RichTextUploadingField(config_name='post_ckeditor')
comment_count = models.IntegerField(default=0)
view_count = models.IntegerField(default=0)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
thumbnail = models.ImageField()
categories = models.ManyToManyField(Category)
featured = models.BooleanField()
previous_post = models.ForeignKey('self', related_name='previous', on_delete=models.SET_NULL, blank = True, null = True)
next_post = models.ForeignKey('self', related_name='next', on_delete=models.SET_NULL, blank = True, null = True)
My views.py
def get_author(user):
qs = Author.objects.filter(user=user)
if qs.exists():
return qs[0]
return None
pass
def post_create(request):
form = PostForm(request.POST or None, request.FILES or None)
author= get_author(request.user)
if request.method == 'POST':
if form.is_valid():
form.instance.author = author
form.save()
return redirect(reverse('post-detail', kwargs={
'id': form.instance.id
}))
context = {
'form': form
}
return render(request, 'post_create.html', context)
pass
My forms.py
from django import forms
from .models import Post, Comment
class PostForm(forms.ModelForm):
content = forms.CharField
class Meta:
model = Post
fields = ('title', 'overview', 'content', 'thumbnail', 'categories', 'featured', 'previous_post', 'next_post')
class CommentForm(forms.ModelForm):
content = forms.CharField(widget=forms.Textarea(attrs={
'class':'form-control',
'placeholder':'Type your comment',
'id':'usercomment',
'rows':4
}))
class Meta:
model = Comment
fields = ('content', )
Please help !
If you are trying to save request.user in the author field you don't need to write the extra methods just do like this.
if request.method == 'POST':
if form.is_valid():
post =form.save(commit=False)
post.author = request.user
post.save()
return redirect(reverse('post-detail', kwargs={'id': post.id }))
Whenever there is a change in model fields or new model added or removed, you should migrate. And pass a default object to foreign key if not null.
I have made a blogger website on Django and I would have a page where the user can see/manage their own posts, so they can edit, update and delete.
I have tried to add the page but it keeps throwing an error saying no reverse match?
I am sure how to solve this problem, is something to do with how I have added the author in the Post model to PostAuthor?
This is my models file
class PostAuthor(models.Model):
user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True)
bio = models.TextField(max_length=400, help_text="Enter your bio details here.")
class Meta:
ordering = ["user", "bio"]
def get_absolute_url(self):
return reverse('post-by-author', args=[str(self.id)])
def __str__(self):
return self.user.username
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(PostAuthor, on_delete=models.CASCADE, null=True, blank=True)
updated_on = models.DateTimeField(auto_now=True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
class Meta:
ordering = ['-created_on']
def get_absolute_url(self):
return reverse('post-detail', args=[str(self.id)])
def __str__(self):
return self.title
URLs file
urlpatterns = [
path('', views.IndexPage.as_view(), name='index'),
path('posts/', views.PostList.as_view(), name='all-posts'),
path('blog/<int:pk>', views.PostDetail.as_view(), name='post-detail'),
path('blog/<int:pk>', views.PostListbyAuthorView.as_view(), name='post-by-author'),
path('accounts/', include('django.contrib.auth.urls')),
]
Views file
class PostListbyAuthorView(generic.ListView):
model = Post
template_name = 'blog/post_list_by_author.html'
def get_queryset(self):
id = self.kwargs['pk']
target_author = get_object_or_404(PostAuthor, pk=id)
return Post.objects.filter(author=target_author)
def get_context_data(self, **kwargs):
context = super(PostListbyAuthorView, self).get_context_data(**kwargs)
context['blog'] = get_object_or_404(PostAuthor, pk=self.kwargs['pk'])
return context
class IndexPage(generic.ListView):
queryset = Post.objects.filter(status=1).order_by('-created_on')
template_name = 'blog/index.html'
class PostList(generic.ListView):
queryset = Post.objects.filter(status=1).order_by('-created_on')
template_name = 'blog/all_posts.html'
class PostDetail(generic.DetailView):
model = Post
template_name = 'blog/post_detail.html'
You are not passing the user's ID on your link, try this:
{% url 'post-by-author' pk=user.id %}
Good day everybody.
I need to test a view, and I got stuck ( I am a django newbie).
I got through all other url and view tests, but I'm really not sure how to write this one.
I tried writing it on my own, I read through the testing docs, I even tried testing this using model_mommy ( but I got a custom HTML field in my models ) which is not supported by mommy. I tried with mommy Recipes, also without luck. I really gotta do this test today, it's a part of a task I was given.
here is the view :
class CommentCreateView(CreateView):
def get(self, request, *args, **kwargs):
context = {'form': CommentForm()}
return render(request, 'news/add_comment_to_article.html', context)
def post(self, request, *args, **kwargs):
form = CommentForm(request.POST)
if form.is_valid():
article = get_object_or_404(Article, pk=kwargs.get('pk'))
print(article)
comment = form.save(commit=False)
comment.post = article
comment.save()
return HttpResponseRedirect(reverse('news:article', kwargs={'article_id': article.pk}))
else:
form = CommentForm()
return render(request, 'news/add_comment_to_article.html', {'form': form})
and here are my models:
class Article(models.Model):
title = models.CharField('title', max_length=200, blank=True)
slug = AutoSlugField(populate_from='title', default="",
always_update=True, unique=True)
author = models.CharField('Author', max_length=200, default="")
description = HTMLField()
is_published = models.BooleanField(default=False)
article_text = HTMLField('Article text', default="")
pub_date = models.DateTimeField(default=datetime.now, blank=True)
article_category = models.ForeignKey(Category, on_delete="models.CASCADE", blank=True, null=True, default="")
my_order = models.PositiveIntegerField(default=0, blank=False, null=False)
class Meta(object):
ordering = ['my_order']
def __str__(self):
print(self.image.all())
return self.title
class ArticleImages(models.Model):
article = models.ForeignKey(Article, on_delete="models.CASCADE", related_name="image")
image = models.ImageField("image")
my_order = models.PositiveIntegerField(default=0, blank=False, null=False)
def image_tag(self):
return mark_safe('<img src="/media/%s" width="150" height="150" />' % (self.image))
image_tag.short_description = 'Image'
class Meta(object):
ordering = ['my_order']
def __str__(self):
return self.image.url
class Comment(models.Model):
post = models.ForeignKey('Article', on_delete=models.CASCADE, related_name='comments')
author = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=datetime.now, blank=True)
approved_comment = models.BooleanField(default=False)
def approve(self):
self.approved_comment = True
self.save()
def __str__(self):
return self.text
I would REALLY appreciate someone helping me out here.
Thank you, and have a good day !
I use to django for my web site. But ı have a question about blog/urls.py(my app name is blog )
I use to with one to many releationship in blog/models.py.
Category (1 => *) Subject (1 => *) Article.
class Category(models.Model):
name = models.CharField(max_length=200)
statement = models.TextField()
slug=models.SlugField()
page_name = models.ForeignKey('Page', on_delete=models.CASCADE)
def __str__(self):
return self.name
class Subject(models.Model):
name = models.CharField(max_length=200)
statement = models.TextField()
slug=models.SlugField()
category_name = models.ForeignKey('Category', on_delete=models.CASCADE)
def __str__(self):
return self.name
class Article(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=200)
slug=models.SlugField()
text = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
subject_name = models.ForeignKey('Subject', on_delete=models.CASCADE)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('blog:detail', kwargs={'id' : self.id})
blog/views.py
def detail(request,article_slug):
article = get_object_or_404(Article, slug=article_slug)
article_list=Article.objects .all()
subject_list = Subject.objects.all()
context={
'article': article,
'article_list':article_list,
'subject_list': subject_list
}
return render(request, 'blog/detail.html', context)
blog/urls.py
url(r'^(?P<category_slug>[\w-]+)/(?P<subject_slug>[\w-]+)/(?P<article_slug>[\w-]+)/$', views.detail, name='detail'),
I want to see the url when I click on the links of my article
http://127.0.0.1:8000/myworkandresearch/category_slug/subject_slug/article_slug
blog / urls.py 'How can I edit?
edit my blog/models.py
class Article(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=200)
slug=models.SlugField()
text = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
subject_name = models.ForeignKey('Subject', on_delete=models.CASCADE)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('blog:detail', args=[self.slug, self.subject.slug, self.subject.category.slug])
blog/views.py
def detail(request, category_slug, subject_slug, article_slug):
article = Article.objects.filter(
slug = article_slug,
subject__slug = subject_slug,
subject__category__slug = category_slug
)
subject_list = Subject.objects.all()
category_list = Category.objects.all()
context = {
'category_list': category_list,
'subject_list': subject_list,
'article': article
}
return render(request, 'blog/detail.html', context)
blog/urls.py
from django.conf.urls import include, url
from . import views
app_name = 'blog'
urlpatterns = [
url(r'^$', views.myworkandresearch, name='myworkandresearch'),
url(r'(?P<category_slug>[\w-]+)/$', views.subjects, name='subjects'),
url(r'^(?P<category_slug>[\w-]+)/(?P<subject_slug>[\w-]+)/(?P<article_slug>[\w-]+)/$', views.detail, name='detail'),
]
subjects.html
{% for article in subject.article_set.all %}}
<ul class="sidebar-items">
<li>{{article.title}}</li>
</ul>
{% endfor %}
[error continues.][2]
Page not found (404) Request Method: GET Request
URL: http://127.0.0.1:8000/myworkandresearch/machine_learning/python_dictionary/numpy/ Raised by: blog.views.subjects No Category matches the given query.
You're seeing this error because you have DEBUG = True in your Django
settings file. Change that to False, and Django will display a
standard 404 page.
I think you should have a detail view as
def detail(request, category_slug, subject_slug, article_slug):
article = Article.objects.filter(
slug = article_slug,
subject__slug = subject_slug,
subject__category__slug = category_slug
)
return render(request, 'blog/detail.html', {'article': article})
You need the following method on your article model
def get_absolute_url(self):
return reverse('detail', args=[self.slug, self.subject.slug, self.subject.category.slug])
When displaying your articles
{{article.title}}
Your url might look like this
url(r'^myworkandreseach/(?P<category_slug>[\w-]+)/(?P<subject_slug>[\w-]+)/(?P<article_slug>[\w-]+)/$', views.detail, name='detail'),
Be sure to import views