from news import views
path('archive/', views.archive, name='news-archive')
from django.urls import reverse
reverse('news-archive')
# Можно так:
def get_absolute_url(self):
return "/people/%i/" % self.id
# Но лучше так:
def get_absolute_url(self):
from django.urls import reverse
return reverse('people.views.details', args=[str(self.id)])
<a href="{{ object.get_absolute_url }}">{{ object.name }}</a>
<!-- Так не надо делать -->
<a href="/language/category/product/{{product.pk}}">Link</a>
<!-- надо так -->
<a href="{{product.get_absolute_url}}">Link</a>
urlpatterns = [
path('articles/<int:year>/<int:month>/<int:day>/', views.day_archive, name='day_archive'),
...
]
def ...
year = request.POST.get("year")
month = request.POST.get("month")
day = request.POST.get("day")
return HttpResponseRedirect('articles/' + year + '/' + month + '/' + day + '/')
from django.urls import reverse
def ...
year = request.POST.get("year")
month = request.POST.get("month")
day = request.POST.get("day")
return HttpResponseRedirect(reverse('day_archive', args=[year, month, day]))
# MyUser
from django.contrib.auth.models import AbstractUser
from django.db import models
class MyUser(AbstractUser):
# ...
class Meta:
swappable = 'AUTH_USER_MODEL'
# MyUserCreationForm
from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import MyUser
class MyUserCreationForm(UserCreationForm):
class Meta:
model = MyUser
fields = ('username', 'password1', '...')
# view
from django.urls import reverse_lazy
from django.views.generic.edit import CreateView
from .forms import MyUserCreationForm
from .models import MyUser
class MyUserCreateView(CreateView):
model = MyUser
form_class = MyUserCreationForm
template_name = 'registration/registration_form.html'
success_url = reverse_lazy('blog:index')
# urls
from django.urls import path, include
from .views import MyUserCreateView
urlpatterns = [
path('auth/', include('django.contrib.auth.urls')),
path('auth/registration/', MyUserCreateView.as_view(), name='registration'),
]
class PostListView(ListMixin, ListView):model = Post
ordering = '-pub_date'
paginate_by = 10
template_name = 'blog/index.html'
def get_queryset(self):
queryset = super().get_queryset().all( ).annotate(comment_count=Count("comments"))
if self.request.user.is_authenticated # Проверяем пользователь авторизованный или нет
return queryset.filter(author=self.request.user)
return queryset.filter(category__is_published=True,
is_published=True,
pub_date__lte=timezone.now())
def get_queryset(self):
queryset = super().get_queryset().all( ).annotate(comment_count=Count("comments"))
if self.request.user.is_authenticated # Проверяем пользователь авторизованный или нет
queryset = queryset.filter(author=self.request.user)
if not queryset: # либо можно так - if not len(queryset):
queryset = queryset.filter(category__is_published=True,
is_published=True,
pub_date__lte=timezone.now())
return queryset
class User(models.Model):
....
is_author = models.BooleanField(default=False)
...
...
def get_queryset(self):
queryset = super().get_queryset().all( ).annotate(comment_count=Count("comments"))
if self.request.user.is_authenticated and self.request.user.is_author:
return queryset.filter(author=self.request.user)
return queryset.filter(category__is_published=True,
is_published=True,
pub_date__lte=timezone.now())
class ModelBase(models.Model):
title = models.CharField(_("Название"), max_length=250, blank=False)
def __str__(self):
return self.title
class Model(ModelBase):
some = models.CharField(_("Что то "), max_length=250)
class Model1(ModelBase):
some = models.CharField(_("Что то "), max_length=250)
m = models.ForeignKey(Model, on_delete=models.CASCADE)
class Model2(ModelBase):
some = models.CharField(_("Что то "), max_length=250)
m1 = models.ForeignKey(Model1, on_delete=models.CASCADE)
class Model3(ModelBase):
some = models.CharField(_("Что то "), max_length=250)
m2 = models.ForeignKey(Model2, on_delete=models.CASCADE)
from core.models import *
m1 = Model.objects.all()
m1[0].model1_set
<django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager object at 0x00000296EFFAAE20>
m1[0].model1_set.all()[0].model2_set.all()[0].model3_set.all()[0].some
'some m3'
Post.objects.filter(cat__id=1)
. Тут был пример фильтрации постов, у которых категория с id=1. То есть мы ищем посты у которых категория самая первая (по id).Если мы хотим обраться через Category к модели Post (обратная связь), то тут надо использовать менеджер обратной связи ( [имя вторичной модели]_set или использовать свойство related_name, если оно определено у поля cat ). К примеру: cat = Category.objects.get(id=1) - получение категории с id=1
slug_field¶
The name of the field on the model that contains the slug. By default, slug_field is 'slug'.
slug_url_kwarg¶
The name of the URLConf keyword argument that contains the slug. By default, slug_url_kwarg is 'slug'.
urlpatterns = [ path("<slug:slug>/", ArticleDetailView.as_view(), name="article-detail"), ]