Unable to show user specific link to specific page in django - python

I would like to create user specific links. I mean, when user signed up and logged in, he has redirected to create/ page. In that page user fills out the form and after pressing button, user has to redirect to list/ page, where there are user specific links to specific page, which contain schedule. Schedul appered from data, which user provided in create/ form.
So my problem is, when I filled out the form and redirect to list/ page, there are no links.
My code:
models.py
from django.db import models
from django.contrib.auth.models import User
class File(models.Model):
file = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
#Further, they are fileds, which is nececary to create schedule.
#title = models.CharField('Название Графика', max_length = 50)
#x_title = models.CharField('Название Оси Х', max_length = 50)
#y_title = models.CharField('Название Оси Y', max_length = 50)
#etc...
views.py:
def create(request):
error = ''
if request.method == 'POST':
form = FileForm(request.POST)
if form.is_valid():
form.save()
return redirect('grafic:list')
else:
error = 'Форма была неверной('
form = FileForm()
data = {
'form': form,
'error': error,
}
return render(request, 'graf/create.html', data)
def list(request):
qs = File.objects.filter(file=request.user)
context = {
'user': request.user,
'qs': qs,
}
return render(request, 'graf/list.html', context)
list.html
{% extends 'base.html' %}
{% block content %}
{% if user.is_authenticated %}
<h2>{% block title %} Profile {% endblock %}</h2>
<p>Username: {{ user }}</p>
{% for b in qs %}
<article class="card">
<div class="card_wrapper">
<figure class="card_feature">
</figure>
<div class="card_box">
<a href="{% url 'grafic:index' b.id %}">
<header class="card_item card_header">
<h6 class="card__item card__item--small card__label">Твой график</h6>
<a class="card__item card__item--small card__title" href="{% url 'grafic:index' b.id %}">
{{b.graf_title}}
</a>
</header>
<hr class="card__item card__divider">
</a>
</div>
</div>
</article>
{% endfor %}
{% endif %}
{% endblock %}
urls.py
from django.urls import path
from . import views
app_name = 'grafic'
urlpatterns = [
path('', views.first, name = 'first'),
path('create/', views.main, name = 'main'),
path('list/', views.list, name = 'list'),
path('files/<int:grafics>', views.index, name = 'index'),
path('login/', views.loginpage, name = 'loginpage'),
path('register/', views.registerpage, name = 'registerpage'),
]
That's all. Sorry if my code is such inconvenient. Thank you in advance for your cooperation)
enter image description here
That is my problem. In the 'file' field there are no user.

Related

Django: child model edit comment not working

I got problem with my edit comments when i press the edit comment from the template i get no error but is redirected to the top of the same page. Anyone got any idea how i can get it to allow me to edit the comment?
This post is edited with only the code needed and i fixed the delete comment from before so that code is removed.
Here is my code:
views.py:
from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.db.models.functions import Lower
from .models import Product, Category, Review
from .forms import ProductForm, ReviewForm
def product_detail(request, product_id):
product = get_object_or_404(Product, pk=product_id)
if request.method == 'POST':
rating = request.POST.get('rating', 3)
content = request.POST.get('content', '')
Review.objects.create(
product=product,
rating=rating,
content=content,
created_by=request.user
)
# redirect to the same page
return redirect('product_detail', product_id=product_id)
reviews = Review.objects.filter(product=product)
context = {
'product': product,
'reviews': reviews
}
return render(request, 'products/product_detail.html', context)
#login_required
def edit_review(request, review_id):
"""
Saves review form edited by user
"""
review = get_object_or_404(Review, pk=review_id)
product = Product.objects.get(name=review.product)
if request.method == 'POST':
review_form = ReviewForm(request.POST or None, instance=review)
if review_form.is_valid():
review_form.save()
messages.success(request, 'Successfully updated product!')
return redirect(reverse('product_detail', args=[product.id]))
# Success message if added
messages.success(request, 'Thank You! Review was edited')
else:
# Error message if form was invalid
messages.error(request, 'Something went wrong. '
'Make sure the form is valid.')
form = ReviewForm(instance=review)
messages.info(request, f'You are editing {review_id}')
template = 'products/edit_review.html'
context = {
'form': form,
'product': review,
}
return redirect(reverse('product_detail', args=[product.id]))
models.py:
from django.db import models
from django.contrib.auth.models import User
class Review(models.Model):
product = models.ForeignKey(Product, related_name='reviews', on_delete=models.CASCADE)
rating = models.IntegerField(default=3)
content = models.TextField()
created_by = models.ForeignKey(User, related_name='reviews', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s - %s' % (self.product.name, self.created_by)
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.all_products, name='products'),
path('<int:product_id>/', views.product_detail, name='product_detail'),
path('add/', views.add_product, name='add_product'),
path('edit/<int:product_id>/', views.edit_product, name='edit_product'),
path('delete/<int:product_id>/', views.delete_product, name='delete_product'),
path('delete_review/<int:review_id>/delete_review', views.delete_review, name='delete-review'),
path('edit_review/<review_id>', views.edit_review, name="edit_review"),
]
forms.py:
from django import forms
from .widgets import CustomClearableFileInput
from .models import Product, Category, Review
class ReviewForm(forms.ModelForm):
class Meta:
model = Review
fields = ('content', 'rating')
widgets = {
'content': forms.Textarea(attrs={'class': 'form-control'}),
'rating': forms.Select(attrs={'class': 'form-control'}),
}
edit_review.html template
{% extends "base.html" %}
{% load static %}
{% block content %}
<div class="overlay"></div>
<div class="container">
<div class="row">
<div class="col-12 col-md-6">
<hr>
<h2 class="logo-font mb-4">Reviews</h2>
<h5 class="text-muted">Edit you're Review</h5>
<hr>
</div>
</div>
<div class="row">
<div class="col-12 col-md-6">
<form method="POST" action="{% url 'edit_review' review.id %}" class="form mb-2" enctype="multipart/form-data">
{% csrf_token %}
{% for field in form %}
{% if field.name != 'image' %}
{{ field | as_crispy_field }}
{% else %}
{{ field }}
{% endif %}
{% endfor %}
<div class="text-right">
<a class="btn btn-outline-black rounded-0" href="{% url 'reviews' %}">Cancel</a>
<button class="btn btn-black rounded-0" type="submit">Update Review</button>
</div>
</form>
</div>
</div>
</div>
{% endblock %}
for the first problem in the delete view you must refer to the model with capital Review
#login_required
def delete_review(request, review_id):
review = Review.objects.filter(review_id).last()
For the second problem you can see detailed information about this error and how to handle it, from Here

Error when returning multiple return statements in a Django view, 'tuple' object has no attribute 'get.'| cs50 web project 4 (network)

I am working on CS50 Network and am supposed to design a Twitter-like social network website for making posts and following users. In my view's return statement I am trying to render a page and a jsonrespone. The JsonResponse is so javascript can access it. The error I get is: 'tuple' object has no attribute 'get.'
error
view (this shows a page of all the posts specific to a user. When a logged in user clicks on the username of a post it passes values. This is how the parameters in the view gets its values.):
def profile(request, user_id, username):
# list number of followers and following
profiles = Profile.objects.all()
# get all posts and order them
posts = Post.objects.filter(user=user_id).order_by('-timestamp')
# pagination
pagination = Paginator(posts, 10)
page_num = request.GET.get('page')
try:
pages = pagination.page(page_num)
except EmptyPage and PageNotAnInteger:
pages = pagination.page(1)
# serialize
json_posts = serializers.get_serializer("json")().serialize(posts)
return render(request, "network/profile.html", {
"posts": pages,
"user_id": user_id,
"username": username,
"profiles": profiles,
"currentUser": request.user,
}), JsonResponse(json_posts, safe=False)
models:
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils import timezone
class User(AbstractUser):
pass
class Profile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Followers_user")
followers = models.ManyToManyField(User, blank=True, null=True,
related_name="Followers_followers")
following = models.ManyToManyField(User, blank=True, null=True,
related_name="Followers_following")
def __str__(self):
return str(self.user)
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Post_user")
text = models.CharField(max_length=280)
timestamp = models.DateTimeField(default=timezone.now)
likes = models.ManyToManyField(User, blank=True, null=True, related_name="Post_likes")
def __str__(self):
return self.text + ' | ' + str(self.user)
urls:
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("profile/<int:user_id>/<str:username>", views.profile, name="profile"),
path("following/<int:user_id>", views.following, name="following"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
]
Relevant html:
<h1 id="username">{{ username }}</h1>
{% for profile in profiles %}
{% if profile.id == user_id %}
<h2>followers: {{ profile.followers.count }}</h2>
<h2>following: {{ profile.following.count }}</h2>
{% endif %}
{% endfor %}
{% if currentUser != username and currentUser.is_authenticated %}
<button class="btn btn-primary" id="follow">Follow</button>
{% endif %}
<div class="card text-center">
{% for post in posts %}
<div id="all-posts">
<div class="card-body">
<a><h5 class="card-title">{{ post.user }}</h5></a>
<p class="card-text">{{ post.text }}.</p>
<button class="btn btn-primary like">0</button>
{% if currentUser == post.user %}
<button class="btn btn-primary edit" id="edit">Edit</button>
{% endif %}
</div>
<div class="card-footer text-muted">
{{ post.timestamp }}
</div>
</div>
<hr>
{% endfor %}
{{ json_posts }}
</div>
<nav aria-label="Page navigation example">
<ul class="pagination">
{% if posts.has_previous %}
<li class="page-item"><a class="page-link" href="{% url 'profile' %}?page={{posts.previous_page_number}}">Previous</a></li>
{% endif %}
{% if posts.has_next %}
<li class="page-item"><a class="page-link" href="{% url 'profile' %}?page={{posts.next_page_number}}">Next</a></li>
{% endif %}
</ul>
</nav>
You are getting this error because you are returning more that one value in your return statement in the profile view. Django expects only one.
def function():
return 1, 3
type(function()) # <class 'tuple'>
def function1():
return 1
type(function1()) # <class 'int'>
This is the reason you are getting 'tuple' object has no attribute 'get.'
You can simply solve it by only returning one value for each view
def profile(request, user_id, username):
# list number of followers and following
profiles = Profile.objects.all()
# get all posts and order them
posts = Post.objects.filter(user=user_id).order_by('-timestamp')
# pagination
pagination = Paginator(posts, 10)
page_num = request.GET.get('page')
try:
pages = pagination.page(page_num)
except EmptyPage and PageNotAnInteger:
pages = pagination.page(1)
return render(request, "network/profile.html", {
"posts": pages,
"user_id": user_id,
"username": username,
"profiles": profiles,
"currentUser": request.user,
})
and make separate view for JsonResponse
def profile(request, user_id, username):
# list number of followers and following
profiles = Profile.objects.all()
# get all posts and order them
posts = Post.objects.filter(user=user_id).order_by('-timestamp')
# pagination
pagination = Paginator(posts, 10)
page_num = request.GET.get('page')
try:
pages = pagination.page(page_num)
except EmptyPage and PageNotAnInteger:
pages = pagination.page(1)
# serialize
json_posts = serializers.get_serializer("json")().serialize(posts)
return JsonResponse(json_posts, safe=False)

Django category didn't work corrctly href not work

I have made a script to display all posts in a category so, when I try to open the single category it didn't open the page and show the article page, I've followed a tutorial for making this code, the link is: https://www.youtube.com/watch?v=o6yYygu-vvk .
Models.py
from django.db import models
from django import forms
from django.contrib.auth.models import User
from django.urls import reverse
# Categorie
class Category(models.Model):
class Meta:
verbose_name = 'category'
verbose_name_plural = 'categories'
name = models.CharField('Titolo', max_length = 250)
slug = models.SlugField(max_length = 250, unique = True)
desc = models.TextField('Descrizione', max_length=10000, blank=True)
def get_absolute_url(self):
return reverse("blog:CategoryList", args=[self.slug])
def __str__(self):
return self.name
# Articles
class Article(models.Model):
class Meta:
verbose_name = 'Articolo'
verbose_name_plural = 'Articoli'
'''
Classe per creare articoli generali con media
'''
title = models.CharField('Titolo', max_length=100)
author = models.ForeignKey(User, on_delete=models.CASCADE,)
category = models.ForeignKey (Category, on_delete=models.CASCADE)
desc = models.CharField('Descrizione', max_length=10000, blank=True)
text = models.TextField('Testo', max_length=10000, blank=True)
image = models.ImageField('Foto', blank=True, upload_to="img")
data = models.DateTimeField('Data di pubblicazione', blank=True)
slug = models.SlugField(max_length = 250, null = True, blank = True, unique=True)
class Meta: # Order post by date
ordering = ['-data',]
def __str__(self):
return "Crea un nuovo articolo"
Views.py
from django.shortcuts import render, get_object_or_404
from django.shortcuts import render
from django.http import HttpResponse
from .models import *
from django.views.generic import View
from django.views import generic
def index(request): # HomePage
articles = Article.objects.all().order_by('-data')[0:3] # Show last 3 articles
return render(request, 'blog/index.php', {'articles':articles})
# Post
def PostList(request): # Articles List
articles = Article.objects.all().order_by('-data')
return render(request, 'blog/post/PostList.php',{'articles':articles})
class PostDetail(generic.DetailView): #Single Article
model = Article
template_name = 'blog/post/post_detail.php'
# Category
def Categories(request): # Category List
categories = Category.objects.all()
return render(request, 'blog/category/category.php',{'categories':categories})
def CategoryList(request, slug): # Show post by category
categories = Category.objects.all()
articles = Article.objects.all()
if slug:
category = get_object_or_404(Category, slug=slug)
articles = articles.filter(category=slug)
template = 'blog/category/single_category.php'
context = {'categories':categories, 'articles':articles, 'category': category}
return render(request, template, context)
Urls.py
from django.conf.urls import url
from . import views
from django.contrib import admin
from django.views.generic import ListView, DetailView
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.index, name='index'), # Index
url(r'^all-articles$', views.PostList, name='PostList'), # All Posts
url(r'^category', views.Categories, name='category'), # All Category
url('<slug: slug>/', views.CategoryList, name='category_list'), # Show post by category
path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), # Single Posts
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
post_detail.php
{% extends 'blog/layout.php' %} <!-- Import Content -->
{% block content %} <!-- Start Content -->
<!-- Articles -->
<div class="article">
{% if article.image %}
<img src="{{article.image.url}}" alt="" class="">
{% endif %}
<div class="article__text">
<h1>{% block title %} {{ object.title }} {% endblock title %}</h1>
<p class="article_info"> Scritto da {{ article.author }} il {{
article.data }}</p>
<p class=" article_desc">{{ article.desc }}</p>
<p class=" article_content">{{ article.text }}</p>
<p class=" article_category">category: <a href="{{ articles.category.get_absolute_url
}}">
{{ article.category }}</a></p>
</div>
</div>
{% endblock content %}
single_category.php
{% extends 'blog/layout.php' %} <!-- Import Content -->
<!-- Content -->
{% block content %}
<h1>{{ category.name }}</h1>
{% for article in articles %}
<!--CARDS -->
<section class="cards"clearfix> <a href="{% url 'post_detail' article.slug %}">
<div class="card">
{% if article.image %}
<img src="{{article.image.url}}" alt="" class="card__img">
{% endif %}
<div class="card__txt">
<h3 class="card__title">{{article.title}}</h3>
<p class="date__article"> by {{article.author}}</p>
<p class="card__text">{{article.desc}}</p>
</div>
</div>
</a>
</section>
{% endfor %}
{% endblock %}
Your function to return the url of category is wrong because the name of "CategoryList" don't exists in
class Category():
#---- your properties definition
def get_absolute_url(self):
#bad return reverse("blog:CategoryList", args=[self.slug])
return reverse("blog:category_list", args=[self.slug])
In your urls.py
url('<slug: slug>/', views.CategoryList, name='category_list'), # Show post by category
category_list is defined as name in your url, not ~CategoryList~
AND
You use the same URL for post and category list
url('<slug: slug>/', views.CategoryList, name='category_list'), # Show post by category
path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'),
AND You are mixing url and path in the same definition.
So, you probably are use django 2.x and read django 1.x tutorial.
Another think (that the devs was commented)... the extension of html files as php is not good, php is a "program language" and html is another thing... but, you can use any extension...

django error: django.urls.exceptions.NoReverseMatch

I am creating a stock management system for my company. I don't know why the error: NoReverseMatch keeps coming for item_edit and item_delete views or urls. Because of these errors, I am not able to comple my CRUD views and modify or delete a exisiting item.
The Error: "django.urls.exceptions.NoReverseMatch: Reverse for 'stock_management.views.item_edit' not found. "
I have already tried going through my code a lot of time. I have also tried calling reverse() function for item_edit and item_delete from the shell and I also have also tried to manually enter the URLs in the browser but still the same error keeps showing.
My models:
class Item(models.Model):
GOLD_PURITY_CHOICES = (
...
)
COLOUR_CHOICES = (
...
)
DIAMOND_PURITY_CHOICES = (
...
)
RATING_CHOICES = (
...
)
code = models.CharField(max_length=25, db_index=True, unique=True)
gold_purity = models.CharField(
max_length=3, choices=GOLD_PURITY_CHOICES, default='14K')
labour = models.PositiveIntegerField()
certification_no = models.CharField(max_length=35, null=True, blank=True)
diamond_colour = models.CharField(
max_length=4, choices=COLOUR_CHOICES, default='F')
diamond_purity = models.CharField(
max_length=10, choices=DIAMOND_PURITY_CHOICES, default='IF')
rating = models.CharField(
max_length=3, default='A', choices=RATING_CHOICES)
gross = models.DecimalField(max_digits=6, decimal_places=3)
image = models.ImageField(blank=True, null=True,
upload_to=user_directory_path)
def __str__(self):
...
class Color(models.Model):
item = models.ForeignKey(
Item, on_delete=models.CASCADE, related_name='colors', help_text='Item to which the colors belong.')
shade = models.DecimalField(...)
price = models.IntegerField(...)
class Diamond(models.Model):
item = models.ForeignKey(
Item, on_delete=models.CASCADE, related_name='diamonds', help_text='Item to which the diamond belong.')
weight = models.DecimalField(...)
rate = models.IntegerField(...)
urls.py:
from django.urls import path, include
from .views import *
from django.conf import settings
app_name = 'stock_management'
urlpatterns = [
path('', index, name='homepage'),
path('stock/', stock_list, name='stock_list'),
path('stock/add', stock_create_view, name='add_stock'),
# Item:
path('item/edit/<pk>', item_edit, name='item_edit'),
path('item/delete/<pk>', ItemDeleteView.as_view(), name='item_delete'),
]
if settings.DEBUG:
# test mode
from django.conf.urls.static import static
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
views.py:
def item_edit(request, pk=1):
item = get_object_or_404(Item, pk=pk)
ColorInlineFormSet = inlineformset_factory(
Item, Color, fields=('shade', 'price'), extra=1)
DiamondInlineFormSet = inlineformset_factory(
Item, Diamond, fields=('weight', 'rate'), extra=1)
if request.method == 'POST':
color_inline_formset = ColorInlineFormSet(
request.POST, instance=item)
diamond_inline_formset = DiamondInlineFormSet(
request.POST, instance=item)
item_form = ItemForm(request.POST, instance=item)
if item_form.is_valid() and color_inline_formset.is_valid() and diamond_inline_formset.is_valid():
item = item_form.save()
color_formset = color_inline_formset.save()
diamond_formset = diamond_inline_formset.save()
return redirect('stock_management:homepage')
else:
messages.error(request, item_form.errors)
messages.error(request, color_inline_formset.errors)
messages.error(request, diamond_inline_formset.errors)
else:
color_inline_formset = ColorInlineFormSet(
instance=item)
diamond_inline_formset = DiamondInlineFormSet(
instance=item)
item_form = ItemForm(instance=item)
return render(request, 'forms/add_stock.html', {'title': 'Edit Item Form', 'item': item, 'item_form': item_form, 'item_colour_forms': color_inline_formset, 'item_diamond_forms': diamond_inline_formset, })
def item_delete(request, pk):
item = get_object_or_404(Item, pk=pk)
if request.method == 'POST':
item.delete()
return redirect('stock_list')
return render(request, 'forms/utils/confirm_delete.html', {'title': item})
templates:
list.html:
{% extends 'index.html' %}
{% block title %} Stock {% endblock %}
{% block pageheading %} Stock List {% endblock %}
{% block content %}
{% for stock in stocks %}
<div class="card-body">
<div class="item pb-1">
<h5>{{ stock.item.code }}</h5>
{% if stock.item.image %}
<image src = " {{ stock.item.image.url }} " ></image>
{% endif %}
<a href=" {% url 'item_delete' stock.item.id %} " class="btn btn-danger btn-circle">
<i class="fas fa-trash"></i>
</a>
<a href="{% url 'item_edit' pk=stock.item.id %}" class="btn btn-info btn-circle">
<i class="far fa-edit"></i>
</a>
</div>
{% endfor %}
{% endblock %}
I want the error to be resolved so that I can complete my CRUD views and also can access my list.html again.
You need to add your appname with used urls in your html files when using urls.
Also update
<a href=" {% url 'stock_management:item_delete' pk=stock.item.id %}
to
<a href=" {% url 'stock_management:item_delete' stock.item.id %}
You code should looks like that:
{% extends 'index.html' %}
{% block title %} Stock {% endblock %}
{% block pageheading %} Stock List {% endblock %}
{% block content %}
{% for stock in stocks %}
<div class="card-body">
<div class="item pb-1">
<h5>{{ stock.item.code }}</h5>
{% if stock.item.image %}
<image src = " {{ stock.item.image.url }} " ></image>
{% endif %}
<a href=" {% url 'stock_management:item_delete' stock.item.id %} " class="btn btn-danger btn-circle">
<i class="fas fa-trash"></i>
</a>
<a href="{% url 'stock_management:item_edit' stock.item.id %}" class="btn btn-info btn-circle">
<i class="far fa-edit"></i>
</a>
</div>
{% endfor %}
{% endblock %}

Posts from admin panel on different subpages

I would like to add post list from main page to another subpages. (main page to subpage called "programowanie")
For example:
I have a website wwww.example.com. On this website I have a post list that is generated from admin panel (I can add, delete a posts using admin panel).
The problem is that when I try to copy templates from start page with post list to other subpage (called: www.example.com/programowanie) it doeasn't work (I see a template from main page but without post list)
I think the problem is in templates/blog/post/list.html in loop {% for post in posts %}
If I solve this problem I would like to add in admin panel different overlap to publish posts only in "programowanie" subpage.
This is my files:
blog/views.py
from django.shortcuts import render, get_object_or_404, HttpResponse
from .models import Post, Posta, Comment
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.generic import ListView
from .forms import EmailPostForm, CommentForm
from django.core.mail import send_mail
from taggit.models import Tag
from django.db.models import Count
def post_share(request, post_id):
# Pobranie posta na podstawie jego identyfikatora.
post = get_object_or_404(Post, id=post_id, status='published')
sent = False
if request.method == 'POST':
# Formularz został wysłany.
form = EmailPostForm(request.POST)
if form.is_valid():
# Weryfikacja pól formularza zakończyła się powodzeniem…
cd = form.cleaned_data
post_url = request.build_absolute_uri(
post.get_absolute_url())
subject = '{} ({}) zachęca do przeczytania "{}"'.format(cd['nick'], cd['email'], post.title)
message = 'Przeczytaj post "{}" na stronie {}\n\n Komentarz dodany przez {}: {}'.format(post.title, post_url, cd['nick'], cd['komentarz'])
send_mail(subject, message, 'admin#myblog.com', [cd['adresat']])
sent = True
else:
form = EmailPostForm()
return render(request, 'blog/post/share.html', {'post': post,
'form': form,
'sent': sent})
class PostListView(ListView):
queryset = Post.published.all()
context_object_name = 'posts'
paginate_by = 3
template_name = 'blog/post/list.html'
def post_list(request, tag_slug=None):
object_list = Post.published.all()
tag = None
if tag_slug:
tag = get_object_or_404(Tag, slug=tag_slug)
object_list = object_list.filter(tags__in=[tag])
paginator = Paginator(object_list, 3) # Trzy posty na każdej stronie.
page = request.GET.get('page')
try:
posts = paginator.page(page)
except PageNotAnInteger:
# Jeżeli zmienna page nie jest liczbą całkowitą,
# wówczas pobierana jest pierwsza strona wyników.
posts = paginator.page(1)
except EmptyPage:
# Jeżeli zmienna page ma wartość większą niż numer ostatniej strony
# wyników, wtedy pobierana jest ostatnia strona wyników.
posts = paginator.page(paginator.num_pages)
return render(request,
'blog/post/list.html',
{'page': page,
'posts': posts,
'tag': tag})
def post_detail(request, year, month, day, post):
post = get_object_or_404(Post, slug=post,
status='published',
publish__year=year,
publish__month=month,
publish__day=day)
comments = post.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.post = post
new_comment.save()
else:
comment_form = CommentForm()
# Lista podobnych postów.
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')[:4]
return render(request,
'blog/post/detail.html',
{'post': post,
'comments': comments,
'comment_form': comment_form,
'similar_posts': similar_posts})
def programowanie(request):
return render(request, 'blog/post/base.html')
blog/models.py
# -*- coding: utf-8 -*-
from taggit.managers import TaggableManager
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager,
self).get_queryset()\
.filter(status='published')
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Roboczy'),
('published', 'Opublikowany'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250,
unique_for_date='publish')
author = models.ForeignKey(User,
related_name='blog_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_CHOICES,
default='draft')
objects = models.Manager() # Menedżer domyślny.
published = PublishedManager() # Menedżer niestandardowy.
tags = TaggableManager()
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('blog:post_detail',
args=[self.publish.year,
self.publish.strftime('%m'),
self.publish.strftime('%d'),
self.slug])
class Comment(models.Model):
post = models.ForeignKey(Post, related_name='comments')
name = models.CharField(max_length=80)
email = models.EmailField()
komentarz = 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 'Komentarz dodany przez {} dla posta {}'.format(self.name,
self.post)
blog/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
# Widoki posta.
url(r'^$', views.post_list, name='post_list'),
url(r'^programowanie/$', views.programowanie, name='programowanie'),
#url(r'^$', views.PostListView.as_view(), name='post_list'),
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/'\
r'(?P<post>[-\w]+)/$',
views.post_detail,
name='post_detail'),
url(r'^(?P<post_id>\d+)/share/$', views.post_share,
name='post_share'),
url(r'^tag/(?P<tag_slug>[-\w]+)/$', views.post_list,
name='post_list_by_tag'),
]
urls.py
from django.conf.urls import include, url
from django.contrib import admin
from blog import views
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^about/', views.about, name="about"),
url(r'^programowanie/', views.programowanie, name="programowanie"),
url(r'^algorytmy/', views.algorytmy, name="algorytmy"),
url(r'^kontakt/', views.kontakt, name="kontakt"),
url(r'', include('blog.urls',
namespace='blog',
app_name='blog')),
]
blog/templates/base.html
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
{% include "navbar.html" with page=posts %}
<title>{% block title %}{% endblock %}</title>
<link href="{% static "admin/css/blog.css" %}" rel="stylesheet">
</head>
<body>
<div id="content">
{% block content %}
{% endblock %}
</div>
<div id="sidebar">
<h2>Mój blog</h2>
<p>To jest mój blog.</p>
</div>
</body>
</html>
blog/templates/post/list.html
{% extends "blog/base.html" %}
{% block title %}Mój blog{% endblock %}
{% block content %}
<h1>Mój blog</h1>
{% if tag %}
<h2>Posty oznaczone tagiem "{{ tag.name }}"</h2>
{% endif %}
{% for post in posts %}
<h2>
<a href="{{ post.get_absolute_url }}">
{{ post.title }}
</a>
</h2>
<p class="tags">
Tagi:
{% for tag in post.tags.all %}
<a href="{% url "blog:post_list_by_tag" tag.slug %}">
{{ tag.name }}
</a>
{% if not forloop.last %}, {% endif %}
{% endfor %}
</p>
<p class="date">
Opublikowany {{ post.publish }} przez {{ post.author }}
</p>
{{ post.body|truncatewords_html:30|linebreaks }}
{% endfor %}
{% include "pagination.html" with page=posts %}
{% endblock %}
blog/templates/post/detail.html
{% extends "blog/base.html" %}
{% block title %}{{ post.title }}{% endblock %}
{% block content %}
<h1>{{ post.title }}</h1>
<p class="date">
Opublikowany {{ post.publish }} przez {{ post.author }}
</p>
{{ post.body|linebreaks }}
<p>
<a href="{% url "blog:post_share" post.id %}">
Udostępnij posta
</a>
</p>
<h2>Podobne posty</h2>
{% for post in similar_posts %}
<p>
{{ post.title }}
</p>
{% empty %}
Nie ma podobnych postów.
{% endfor %}
{% with comments.count as total_comments %}
<h2>
{{ total_comments }} komentarz{{ total_comments|pluralize:"y" }}
</h2>
{% endwith %}
{% for comment in comments %}
<div class="comment">
<p class="info">
Komentarz {{ forloop.counter }} dodany przez {{ comment.name }}
{{ comment.created }}
</p>
{{ comment.komentarz|linebreaks }}
</div>
{% empty %}
<p>Nie ma jeszcze żadnych komentarzy.</p>
{% endfor %}
{% if new_comment %}
<h2>Twój komentarz został dodany.</h2>
{% else %}
<h2>Dodaj nowy komentarz</h2>
<form action="." method="post">
{{ comment_form.as_p }}
{% csrf_token %}
<p><input type="submit" value="Dodaj komentarz"></p>
</form>
{% endif %}
{% endblock %}
Thanks for any help !! (I thinking about this third day )
The problem you have it's in the views.
Django template has to be rendered by a view, from this view is where you get the data to be rendered in the template. It doesn't matter which url you want to use and which template you are using in the views. What this means is that you can have different urls pointing to the same template (www.example.com/blog/ or www.example.com/programming/) and both render the same template.
If i understood you right, all you have to do is change this :
url(r'^$', views.post_list, name='post_list'),
url(r'^programowanie/$', views.programowanie, name='programowanie'),
To this:
url(r'^$', views.post_list, name='post_list'),
url(r'^programowanie/$', views.post_list, name='programowanie'),
You can refer to the official Django website in order to get more information about this : https://docs.djangoproject.com/en/2.0/intro/tutorial03/
Thanks for help :)
I solved this problem. There was a problem in urls.py file.

Categories

Resources