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
Related
Why aren't the posts being published in templates?
I'm trying to create a stock blog page and right now in this project, I'm having problems with the template and the views, the thing is that I want to display the posts that have the same charfield as the url, but I don't understand why it is sending me to the else in the template, which says "sorry, this page does not exists"
urls.py (I will only show the relevant one)
from django.urls import path
from app1 import views
from .views import PostView, ArticleDetailView, AddPostView, UpdatePostView, DeletePostView, AddCategoryView, CategoryView, LikeView, MyPostsView, AddCommentView, UpdateCommentView, DeleteCommentView
app_name = 'app1'
urlpatterns = [
path('stock/<str:sym>/', views.StockView, name = 'stock'),
]
views.py
def StockView(request, sym):
stock_posts = Post.objects.filter(stock__symbol=sym.lower())
return render(request, 'app1/stockview.html', {'stock':stock_posts})
models.py
class StockNames(models.Model):
name = models.CharField(max_length=255)
symbol = models.CharField(max_length=255)
def __str__(self):
return self.symbol
class Post(models.Model):
title = models.CharField(max_length= 255)
header_image = models.ImageField(null = True, blank = True, upload_to = 'images/')
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = RichTextField(blank = True, null = True)
#body = models.TextField()
post_date = models.DateField(auto_now_add=True)
category = models.CharField(max_length=255, default='coding')
snippet = models.CharField(max_length=255)
likes = models.ManyToManyField(User, related_name = 'blog_posts')
stock = models.ForeignKey(StockNames, null=True, on_delete=models.CASCADE)
def total_likes(self):
return self.likes.count()
def __str__(self):
return self.title + ' | ' + str(self.author)
def get_absolute_url(self):
return reverse('app1:article-detail', args=(self.id,))
template
{% extends "app1/base.html" %}
{% block body_block %}
{{stocks}}
{% endblock %}
Thanks in advance!!
I have a simple structure Shop_list --> Product_list --> Product_detail
I want to filter Product class object by slug field, but I see zero products.
I think that the problem in get_queryset()
views.py
class HomePageView(ListView):
model = Shop
template_name = 'blog/shop_list.html'
page_kwarg = 'shop'
context_object_name = 'shops'
class ProductListView(ListView):
model = Product
template_name = 'blog/product_list.html'
page_kwarg = 'product'
context_object_name = 'products'
def get_queryset(self):
pattern = str(self.request)
pattern = pattern[1:]
slug = self.model.shop
return Product.objects.filter(shop__slug=pattern)
def produt_detail(request, **kwargs):
print(request)
product = get_object_or_404(Product, pk=kwargs["pk"])
return render(request, 'blog/product_detail.html', {'product': product})
models.py
class Shop(models.Model):
title = models.CharField(max_length=200)
image = models.ImageField(blank=True)
slug = models.SlugField(null=False, default="Shop")
def get_absolute_url(self):
return reverse('product_list', kwargs={'slug': self.slug})
class Product(models.Model):
shop = models.ForeignKey(Shop, on_delete=models.CASCADE, related_name="shop")
title = models.CharField(max_length=200)
price = models.CharField(max_length=200)
period_start = models.DateTimeField(blank=True, null=True)
period_end = models.DateTimeField(blank=True, null=True)
def get_absolute_url(self):
return reverse('product_detail', kwargs={'slug': self.shop.slug, 'pk': self.pk})
urls.py
urlpatterns = [
path('', HomePageView.as_view(), name='shop_list'),
path('<slug:slug>', ProductListView.as_view(), name='product_list'),
path('<slug:slug>/<int:pk>/', views.produt_detail, name='product_detail'),
]
product_list.html
{% for product in products %}
<a href="{% url 'product_detail' product.shop.slug product.shop.pk %}">
...
You filter with:
class ProductListView(ListView):
model = Product
template_name = 'blog/product_list.html'
page_kwarg = 'product'
context_object_name = 'products'
def get_queryset(self):
return Product.objects.filter(shop__slug=self.kwargs['slug'])
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 %}
I am trying to add comment fields to my post-detail view. But as soon i add redirect url after calling save(). This gives me error something like this.
Reverse for 'post-detail' with keyword arguments '{'kwargs': {'slug': 'long-established-fact-that-a-reader-will'}}' not found. 1 pattern(s) tried: ['post/(?P[^/]+)/$']
this is my code
posts/views.py
#login_required
def postDetail(request, slug):
post = get_object_or_404(Post, slug=slug)
latest_post = Post.objects.order_by('-timestamp')[0:4]
form = CommentForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
form.instance.user = request.user
form.instance.post = post
form.save()
return redirect('post-detail', kwargs = {
'slug': post.slug
})
context ={
'form': form,
'post': post,
'latest_post': latest_post
}
return render(request, 'posts/post_detail.html', context)
posts/urls.py
from django.urls import path, include
from django.conf.urls.static import static
from posts.views import index,postDetail, categoryDetail, blog, search
urlpatterns = [
path('', index, name="home"),
path('blog/', blog, name="blog"),
path('search/', search, name='search'),
path('post/<str:slug>/', postDetail, name='post-detail'),
path('category/<slug>/', categoryDetail, name='category-detail'),
]
posts/models.py
from tinymce import HTMLField
from django.db import models
from django.contrib.auth import get_user_model
from slugger import AutoSlugField
from django.urls import reverse
# Create your models here.
User = get_user_model()
def upload_location(instance, filename):
return "%s/%s" %(instance.slug, filename)
class Author(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
def __str__(self):
return self.user.username
class Category(models.Model):
title = models.CharField(max_length=20)
slug = AutoSlugField(populate_from='title')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('category-detail', kwargs={'slug': self.slug})
class Post(models.Model):
title = models.CharField(max_length = 100)
slug = AutoSlugField(populate_from='title')
overview = models.CharField(max_length= 200)
timestamp = models.DateTimeField(auto_now_add=True)
content = HTMLField()
comment_count = models.IntegerField(default=0)
view_count = models.IntegerField(default=0)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
thumbnail = models.ImageField(
upload_to=upload_location,
null=True,
blank=True)
category = 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)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'slug': self.slug})
#property
def get_comments(self):
return self.comments.all().order_by('-timestamp')
class Comment(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now_add=True)
content = models.TextField()
post = models.ForeignKey(Post, related_name='comments',on_delete=models.CASCADE)
def __str__(self):
return self.user.username
In your 4th path, you used <str:slug> - I don't believe the URL catching type str catches the dashes used in slugs.
Try this path instead: path('post/<slug:slug>/', postDetail, name='post-detail'),
EDIT
You are also missing a reverse in your postDetail() redirect:
#login_required
def postDetail(request, slug):
post = get_object_or_404(Post, slug=slug)
latest_post = Post.objects.order_by('-timestamp')[0:4]
form = CommentForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
form.instance.user = request.user
form.instance.post = post
form.save()
return redirect(reverse('main:post-detail', kwargs = {
'slug': post.slug
}))
context ={
'form': form,
'post': post,
'latest_post': latest_post
}
return render(request, 'posts/post_detail.html', context)
https://docs.djangoproject.com/en/2.1/topics/http/urls/#path-converters
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'),