from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class Article(models.Model):
article_title = models.CharField(max_length=100)
article_text = models.TextField()
article_date_create = models.DateTimeField(default=timezone.now)
article_date_modify = models.DateTimeField(default=timezone.now)
article_access = models.BooleanField(default=True)
article_autor = models.ForeignKey(User)
article_tag = models.ManyToManyField(Tags)
from django.views import generic
class FullView(generic.DetailView):
template_name = 'blog/full.html'
model = Article
context_object_name = 'fullpost_blog'
obj = super(FullView, self).get_object()
if self.request.user.is_anonymous and obj.article_access:
raise PermissionDenied
else:
return obj
{% if user.is_authenticated or article.article_access %}
<p>{{ article.article_title }}</p>
<p>{{ article.article_text }}</p>
...
{% else %}
<p>"Данная запись доступна только зарегистрированным пользователям, <a href="{% url 'customer:login' %}">войдите</a> или
<a href="{% url 'customer:register' %}">зарегистрируйтесь".</a></p>
{% endif %}
if request.user.is_authenticated():
...
else:
...
def FullView(request, pk):
obj = get_object_or_404(Article, pk=pk)
@access_private_post(url='/login', access=obj.article_access)
def view(request, obj):
return render(request, 'blog/full.html', {'fullpost_blog': obj})
return view(request, obj)
from functools import wraps
from django.shortcuts import redirect
def access_private_post(function=None, url=None, access=None):
def decorator(function):
@wraps(function)
def wrapper(request, *args, **kwargs):
if not access and not request.user.is_authenticated():
return redirect(url)
else:
return function(request, *args, **kwargs)
return wrapper
return decorator