How do I change a value of a BooleanField in Django? - python

The view class:
class PostCreateView(CreateView):
form_class = PostForm
model = Post
The model class:
class Post(models.Model):
title = models.CharField(max_length=256)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
neg_sentiment = models.BooleanField(default=False)
def get_absolute_url(self):
return reverse('post_detail', kwargs={'pk': self.pk})
def __str__(self):
return self.title
I'm trying to get BooleanField to change to True, but I don't know how to reassign it

urls.py:
urlpatterns = [
path('publish_post/<int:pk>', views.PublishPost, name='publish_post'),
]
views.py:
def PublishPost(request, pk):
post = Post.objects.get(pk=pk)
post.neg_sentiment.save()
post.save()
context = {'success' : True}
return HttpResponse(context)
Then in your template you can set up a post request to 'publish_post' with the id of the post object.

Related

Django url path matching not working as expected

I have problem with Django model get_absolute_url reverse methods.
I have a url pattern that works perfectly but the problem for example
when I visit example.com/blog/python/first-post the path works perfectly, but
when I try a random path like, example.com/blog/python-randomr9353/first-post
it still works correctly even though it shouldn't because, python-randomr9353 is not
a valid path and it should return a page not found error.
Here is my code.
Models
class ArticleSeries(models.Model):
title = models.CharField(max_length=200)
series_slug = AutoSlugField(populate_from='title')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('blog:article_list', kwargs={'series_slug': self.series_slug})
class Tag(models.Model):
title = models.CharField(max_length=50)
def __str__(self):
return self.title
class Article(models.Model):
title = models.CharField(max_length=200)
article_slug = AutoSlugField(populate_from='title')
tag = models.ManyToManyField(Tag, default=1, verbose_name='Tag')
series = models.ForeignKey(ArticleSeries, default=1, verbose_name='Series', on_delete=models.SET_DEFAULT)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('blog:article_detail', args=(self.series.series_slug, self.article_slug))
url patterns
app_name = 'blog'
urlpatterns = [
path('', views.IndexView.as_view(), name='index_view'),
path('blog', views.BlogView.as_view(), name='blog_view'),
path('blog/<slug:series_slug>', views.ArticleListView.as_view(), name='article_list'),
path('blog/<slug:series_slug>/<slug:article_slug>', views.ArticleDetailView.as_view(), name='article_detail'),
]
Views
class IndexView(TemplateView):
template_name = 'blog/index.html'
extra_context = {}
class BlogView(ListView):
model = ArticleSeries
template_name = 'blog/blog_view.html'
context_object_name = 'series_list'
def get_queryset(self):
series = ArticleSeries.objects.all()
return get_list_or_404(series)
class ArticleListView(ListView):
model = Article
template_name = 'blog/article_list.html'
context_object_name = 'article_list'
def get_queryset(self):
slug = self.kwargs['series_slug']
articles = Article.objects.filter(series__series_slug=slug)
return get_list_or_404(articles)
class ArticleDetailView(DetailView):
model = Article
template_name = 'blog/article_detail.html'
context_object_name = 'article'
slug_field = 'article_slug'
slug_url_kwarg = 'article_slug'
def get_object(self, queryset=None):
slug = self.kwargs.get('article_slug')
return get_object_or_404(Article, article_slug=slug)
Try using path('blog/python/<slug:article_slug>', views.ArticleDetailView.as_view(), name='article_detail') in the urls.py instead of path('blog/<slug:series_slug>/<slug:article_slug>', views.ArticleDetailView.as_view(), name='article_detail').
EDIT:
At the point where you obtain the value of series_slug, validate this there itself.
...
validSeries = ['python', 'c', 'cpp', 'js'] # etc
if series_slug not in validSeries:
# Raise a page not found error

get_absolute_url() missing 1 required positional argument: 'self'

I imagine the solution to this can be found i similar topics, however, it seems a little bit different from problems I have seen.
The redirect, in add_post view, should send me to the Post class, where I have a get_absolute_url.
But it happens that I get the following error message: get_absolute_url() missing 1 required positional argument: 'self'
I literally copied the coded form the "Django Projects Cookbook" in case you wanna check it out and try the code yourself.
Thank you.
from django.contrib.auth.decorators import user_passes_test
from django.shortcuts import redirect, render_to_response, get_object_or_404, render
from .models import Post
from .forms import PostForm, CommentForm
#user_passes_test(lambda u: u.is_superuser)
def add_post(request):
form = PostForm(request.POST or None)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.save()
return redirect(Post) # redirect to Post class
return render(request, 'blog/add_post.html',{ 'form': form })
def view_post(request, slug):
post = get_object_or_404(Post, slug=slug)
form = CommentForm(request.POST or None)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect(request.path)
return render(request, 'blog/blog_post.html',{'post': post,'form': form,})
from django.db import models
from django.template.defaultfilters import slugify
from django.contrib.auth.models import User
class Post(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
text = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __unicode__(self):
return self.title
#models.permalink
def get_absolute_url(self): # get_absolute_url
return ('blog_post_detail', (), { 'slug' :self.slug, })
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
class Comment(models.Model):
name = models.CharField(max_length=42)
email = models.EmailField(max_length=75)
website = models.URLField(max_length=200, null=True, blank=True)
text = models.TextField()
post = models.ForeignKey(Post, on_delete=models.CASCADE)
created_on = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.text
You use the Post class, not its object to redirect. You thus need to use post in:
#user_passes_test(lambda u: u.is_superuser)
def add_post(request):
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
form.instance.author = request.user
post = form.save()
return redirect(post)
return render(request, 'blog/add_post.html',{ 'form': form })
The #permalink decorator was removed in Django-2.1, it is advised to use reverse [Django-doc] instead:
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
text = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __unicode__(self):
return self.title
def get_absolute_url(self):
return reverse('blog_post_detail', kwargs={'slug': self.slug})
Furthermore python-2.x is no longer supported since January 1, 2020; so you might want to update to django-3.x in a python-3.x environment.

Generic detail view PostDetailView must be called with either an object pk or a slug in the URLconf

I used get_absolute_url in my model but when I am browsed my post link I got this type error
AttributeError at /blog/details/Hello-World1/
Generic detail view PostDetailView must be called with either an object pk or a slug in the URLconf.
I would like to create link this link /Hello-World1/ (mix with title and pk id)
Models.py
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, models.SET_NULL, null=True, blank=True,)
title = models.CharField(max_length=200)
content = models.TextField()
tags = models.ManyToManyField(Tag)
created_at=models.DateTimeField(auto_now_add=True)
updated_at=models.DateTimeField(auto_now=True)
def get_absolute_url(self):
title = self.title.replace(" ", "-")
return reverse('blog:post_details', args=[title+str(self.id)])
views.py
class PostDetailView(DetailView):
model = Post
template_name = 'blogs/blog_details.html'
urls.py
path('details/<str:new_str>/', PostDetailView.as_view(), name="post_details"),
Your url should have pk arg instead of new_str
path('details/<int:pk>/', PostDetailView.as_view(), name="post_details"),
You need to rewrite get_object
view.py
class PostDetailView(DetailView):
model = Post
template_name = 'blogs/blog_details.html'
def get_object(self, queryset=None):
if queryset is None:
queryset = self.get_queryset()
new_str = self.kwargs.get('new_str') or self.request.GET.get('new_str') or None
queryset = queryset.filter(pk=new_str)
obj = queryset.get()
return obj
see http://www.chenxm.cc/article/1143.html
view.py
class PostDetailView(DetailView):
model = Post
template_name = 'blogs/blog_details.html'
def get_object(self, queryset=None):
if queryset is None:
queryset = self.get_queryset()
new_str = self.kwargs.get('new_str') or self.request.GET.get('new_str') or None
queryset = queryset.filter(pk=new_str)
obj = queryset.get()
return obj
see http://www.chenxm.cc/article/1143.html

How can I make category view to list out all the post with related category in Django using class based views

I want to know how to make category page view using class based view I know how to make this in function based view by using get_object_or_404(category, slug=None) But I am confused how to do this it in class based views. I tried to google this but I am unable to find anything related to this in class view.
I know I could have used function based view but I have used class based view in whole project so I thought to use them here as well
my code
models.py
from django.db import models
from django.utils import timezone
from slugger import AutoSlugField
from django.contrib.auth.models import User
from django.urls import reverse
# Create your models here.
def upload_location(instance, filename):
return "%s/%s" %(instance.slug, filename)
class Category(models.Model):
title = models.CharField(max_length= 60)
slug = AutoSlugField(populate_from='title')
parent = models.ForeignKey('self',blank=True, null=True ,related_name='children',on_delete=models.CASCADE)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
class Meta:
verbose_name_plural = 'categories'
def __unicode__(self):
return self.title
def __str__(self):
return self.title
def get_absolute_url(self, slug=None):
return reverse("posts-detail", kwargs={"slug": self.slug})
class Post(models.Model):
title = models.CharField(max_length=120)
slug = AutoSlugField(populate_from='title')
image = models.ImageField(
upload_to=upload_location,
null=True,
blank=True,
)
category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='postcategory')
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
ordering = ['-date_posted']
def __str__(self):
return self.title
def get_absolute_url(self, slug=None):
return reverse("posts-detail", kwargs={"slug": self.slug})
urls.py
from django.urls import path
from django.urls import path, include
from .views import PostView, PostDetailView,LatestPostView, CategoryPostListView
urlpatterns = [
path('', PostView.as_view(), name='posts-home'),
path('latest/', LatestPostView.as_view(), name='posts-latest'),
path('<slug>', PostDetailView.as_view(), name='posts-detail'),
path('category/<slug>', CategoryPostListView.as_view(), name='category-detail'),
]
views.py
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.shortcuts import redirect, render,get_object_or_404
#class based view
from django.views.generic import ListView, DetailView
from .models import Post, Category
class PostView(ListView):
template_name = 'posts/home.html'
model = Category
context_object_name = 'all_categs'
def get_queryset(self):
if self.request.user.is_authenticated:
return Category.objects.all()
else:
return Category.objects.all().exclude(title__iexact = 'Featured')[:6]
def get_context_data(self):
if not self.request.user.is_authenticated:
fcategory = Category.objects.get(title__iexact = 'Featured')
context = super(PostView, self).get_context_data()
context['latest_posts'] = Post.objects.exclude(category= fcategory).order_by('-date_posted')[0:6]
context['featured_posts'] = Post.objects.all().filter(category= fcategory).order_by('-date_posted')[0:6]
return context
else:
fcategory = Category.objects.get(title__iexact = 'Featured')
context = super(PostView, self).get_context_data()
context['latest_posts'] = Post.objects.order_by('-date_posted')
context['featured_posts'] = Post.objects.all().filter(category= fcategory).order_by('-date_posted')[0:6]
return context
# def get_success_url(self):
# return reverse('home') #add your path
class LatestPostView(LoginRequiredMixin, ListView):
template_name = 'posts/post_latest.html'
model = Post
context_object_name = 'Posts'
ordering = ['-date_posted']
paginate_by = 6
class PostDetailView(LoginRequiredMixin,DetailView):
model = Post
template_name = 'posts/post_detail.html'
class CategoryPostListView(LoginRequiredMixin, ListView):
model = Category
template_name = 'posts/category_detail.html'
# def get_queryset(self):
# category = get_object_or_404(Category, )
I thought of defining get_queryset inside CategoryPostListView. But I am not sure if it will work or not.
Firstly, if you are using ListView and want to display a list of posts, then you need model = Post.
Next, you can call get_object_or_404 in the get_queryset method. You can access slug from the URL with `self.kwargs['slug'].
Finally, you can filter the queryset to only return posts in that category.
class CategoryPostListView(LoginRequiredMixin, ListView):
model = Post
template_name = 'posts/category_detail.html'
def get_queryset(self):
category = get_object_or_404(Category, slug=self.kwargs['slug'])
return super(CategoryPostListView, self).get_queryset().filter(category=category)
Note that your problem is very similar to the dynamic filtering section in the docs.
Yes. you can use get_object_or_404 in class-based views. just add this to your CategoryPostListView:
class CategoryPostListView(LoginRequiredMixin, ListView):
model = Post
template_name = 'posts/category_detail.html'
def get_queryset(self):
category = get_object_or_404(Category, slug=self.kwargs['slug'])
# do another stuffs here
return Post.objects.filter(category=category)
for more information you can read dynamic filtering in class-based views in django official site

Having trouble passing a slug to UpdateView so that it gets the correct data

I am trying to allow a user to edit the information entered into their project using UpdateView. I kept getting an error saying "Generic detail view UpdateProject must be called with either an object pk or a slug." I have tried pointing to the slug within the UpdateView class, but can't get it to work. I am new to Django, so any help would be much appreciated!
views
class CreateProject(CreateView):
model = UserProject
form_class = UserProjectForm
template_name = 'howdidu/create_project.html'
def form_valid(self, form):
userproject = form.save(commit=False)
form.instance.user = self.request.user
userproject.save()
self.object = userproject
return super(CreateProject, self).form_valid(form)
def get_success_url(self):
project_username = self.request.user.username
project_slug = self.object.slug
return reverse('user_project', kwargs={'username':project_username, 'slug': project_slug})
class UpdateProject(UpdateView):
model = UserProject
form_class = UserProjectForm
template_name = 'howdidu/update_project.html'
slug_field = 'slug'
def form_valid(self, form):
userproject = form.save(commit=False)
form.instance.user = self.request.user
userproject.save()
self.object = userproject
return super(UpdateProject, self).form_valid(form)
def get_success_url(self):
project_username = self.request.user.username
project_slug = self.object.slug
return reverse('user_project', kwargs={'username':project_username, 'slug': project_slug})
urls
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^register_profile/$', views.register_profile, name='register_profile'),
url(r'^update_profile/$', views.update_profile, name='update_profile'),
url(r'^create_project/$', login_required(views.CreateProject.as_view()), name='create_project'),
url(r'^update_project/$', login_required(views.UpdateProject.as_view()), name='update_project'),
url(r'^(?P<username>\w+)/$', views.profile_page, name='user_profile'),
url(r'^(?P<username>\w+)/(?P<slug>[-\w]+)/$', views.project_page, name='user_project'),
)
models
class UserProject(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=100)
project_overview = models.CharField(max_length=1000)
project_picture = models.ImageField(upload_to='project_images', blank=True)
date_created = models.DateTimeField(auto_now_add=True)
project_views = models.IntegerField(default=0)
project_likes = models.IntegerField(default=0)
project_followers = models.IntegerField(default=0)
slug = models.SlugField(max_length=100, unique=True) #should this be unique or not?
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(UserProject, self).save(*args, **kwargs)
def __unicode__(self):
return self.title
Django's UpdateView requires pk or slug parameter coming from the corresponding url by default. In your case you need to change the url to your UpdateProject view to
url(r'^update_project/(?P<slug>[-\w]+)/$',
login_required(views.UpdateProject.as_view()),
name='update_project'),
where slug is your project's slug.
create a utils.py file in your app. using slugify from django utils.
import random
import string
from django.utils.text import slugify
def random_string_generator(size=10, chars=string.ascii_lowercase + string.digits):
return "".join(random.choice(chars) for _ in range(size))
def unique_slug_generator(instance, new_slug=None):
if new_slug is None:
slug = new_slug
else:
slug=slugify(instance.model field of your choice)
Klass = instance.__class__
qs_exists = Klass.objects.filter(slug=slug).exists()
if qs_exists:
new_slug = "{slug}-{randstr}".format(
slug=slug,
randstr=random_string_generator(size=4)
)
return unique_slug_generator(instance, new_slug=new_slug)
return slug
add a slug to your model
slug = models.SlugField(null=True, blank=True)
add it to your urls.py file
url(r'^update/(?P<slug>[\w-]+)/$', profileUpdate.as_view(), name='update'),
class UserProject(UpdateView):
model = BlogSlider
fields = ['title', 'sub_title', 'description', 'image']
template_name = 'update.html'
use a form and use {{ form.as_p }}.

Categories

Resources