everything is ok in the model but when I try to retrieve the object the error "No Post matches the given query." is shown.
I don't know what is the problem that shows this error?
**Model**
class Post(CoreField):
....
slug = models.SlugField(max_length=250, unique_for_date='publish')
tags = TaggableManager()
publish = models.DateTimeField(default=timezone.now)
def get_absolute_url(self):
return reverse('news:post_detail',
args=[self.publish.year,
self.publish.month,
self.publish.day,
self.slug])
**url**
path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name='post_detail'),
**views**
def post_detail(request, year, month, day, post):
single_post = get_object_or_404(Post,
publish__year=year,
publish__month=month,
publish__day=day,
slug=post
)
# List of active comments for this post
comments = post.comments.filter(active=True)
# Form for users to comment
form = CommentForm()
return render(request, 'news/post_detail.html', {'post': single_post, 'comments': comments, 'form': form})
when I remove the remove the "int:year/int:month/int:day/" form url it works.
but when I pass the "int:year/int:month/int:day/slug:post/" it does't work.
What is the proble and where it happens????
In your post_detail view, I think you should pass "slug" as an argument to the view instead of "post" because post is not a model field nor is it defined anywhere. And the "slug=post" kwarg should probably be reversed to avoid further errors.
So the post_detail view should probably look like this:
def post_detail(request, year, month, day, slug):
single_post = get_object_or_404(Post,
publish__year=year,
publish__month=month,
publish__day=day,
post=slug
)
Related
Reverse for 'post_detail' with arguments '('chempion',)' not found. 1 pattern(s) tried: ['(?P<category_slug>[-a-zA-Z0-9_]+)/(?P[-a-zA-Z0-9_]+)/$']
as soon as I add function and view to templates I catch this error
view.py
def post_detail(request, category_slug, slug):
post = get_object_or_404(Post, slug=slug)
try:
next_post = post.get_next_by_date_added()
except Post.DoesNotExist:
next_post = None
try:
previous_post = post.get_previous_by_date_added()
except Post.DoesNotExist:
previous_post = None
context = {
'post': post,
'next_post': next_post,
'previous_post': previous_post
}
return render(request, 'post_detail.html', context)
urls.py
path('<slug:category_slug>/<slug:slug>/', post_detail, name='post_detail'),
path('<slug:slug>/', category_detail, name='category_detail'),
post detail.html
{% if next_post %}
Next
{% else %}
This is the last post!
{% endif %}
The post_detail view requires two slugs: one of slug for the category, and one for the post.
If your Post model for example has a ForeignKey to the Category model, you can reference this with:
Next
In your view, you might want to check both the slug for the category and for the post, so:
def post_detail(request, category_slug, slug):
post = get_object_or_404(Post, category__slug=category_slug, slug=slug)
# …
I try to let user add comments to blog post am making...
When I run makemigrations and migrate, everything seemed fine . The form displayed well but shows the following error when I fill the form and click on the submit button.
Django.db.utils.IntegrityError: NOT NULL constraint failed: blog_comment.author_id
Am new to Django and following a tutorial. The tutorial doesn't have users except the super user. I learnt about users and so I let user register to use the blog. The tutorial provided a name field in the form so commenter can enter their name. Here, I want to use the current user for this field(see my models.py below to see how I have done this).
Any help to solve this will be appreciated.
models.py
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,)
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 f'Comment by {self.author} on {self.post}'
forms.py
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('comment',)
views.py
login_required
def post_detail(request, post, pk):
post = get_object_or_404(Post, id=pk, slug=post, status='published')
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.post = post
new_comment.save()
else:
comment_form = CommentForm()
return render(request,
'post_detail.html',
{'post': post,
'comments': comments,
'new_comment': new_comment,
'comment_form': comment_form})
PS: I have seen similar questions like this and deleted my migrations file and re-ran migrations but it didn't still work.
In the if comment.is_valid(): block,
Before;
new_comment.save()
Add,
new_comment.author = request.user
I have a blog website and I have New Post button
this is my post list function
def PostList(request):
post_list = Post.objects.all()
context = {'post_list' : post_list}
return render(request, 'blog/home.html', context)
this is my post detail function
def post_detail(request, slug):
post_detail = Post.objects.get(slug=slug)
context = {'post_detail' : post_detail}
return render(request, 'blog/post_detail.html', context)
and I want to create this function but I dont know how
def post_new(request):
post_new = Post.objects.get()
Can anyone help me I am new to django
I am following a tutorial and I want to create an edit button for my input but when I click the edit button it returns the form but empty:
forms.py
class RecordingForm(forms.ModelForm):
class Meta:
model = Recording
fields = ['component', 'group', 'failure', 'degree_of_failure']
views.py
def edit_recording(request,slug, recording_id):
recording = get_object_or_404(Recording, pk=recording_id)
if request.method == "POST":
form = RecordingForm(request.POST, instance=recording)
if form.is_valid():
recording = form.save(commit=False)
recording.save()
return redirect('data:detail')
else:
form = RecordingForm(instance=recording)
template = 'data/create_recording.html'
context = {'form': form}
return render(request, template, context)
the form is empty :(
The answer is:
Daniel Roseman is correct about GET
And I changed these two in order to fix the NoReverseMatch
plant = get_object_or_404(Plant, slug=slug)
return redirect('data:detail', slug=plant.slug)
In django doc says that
>>> entry = Entry.objects.get(id=10)
is faster than this:
>>> entry = Entry.object.get(headline="News Item Title")
So I changed my view from this:
def myview(request, slug):
post = get_object_or_404(Post, slug=slug)
#...
to this:
def myview(request, id, slug):
post = get_object_or_404(Post, pk=pk)
#...
But my slug is not used in my view. In that case both urls below get the correct post because of valid regex:
127.0.0.1:8000/posts/5/my-first-post/
127.0.0.1:8000/posts/5/mylblablabalg/
And I dont want this. Then I canged my view to this:
def myview(request, id, slug):
post = get_object_or_404(Post, pk=pk)
if post.slug == slug:
return render(request, 'blog/index.html', {'post': post})
else:
return HttpResponseRedirect(reverse('blog:index', args=(id, post.slug)))
It does what I want which redirects the same page with the corrected slug but I doubt if it is ok in terms of performanse. What about db_index? Should I use it in SlugField?
If you are going to pull posts from the database via the SlugField, then yes, you should tell the database to index that field for performance increase. You should also set it to unique.