slug not auto generate after add page in django - python

I tried to add page for posts blog article for my django site.But it's slug model is not autogenerate after add it into the add post page but it work well in admin page.
example in title field when i type how to master python fastly it will auto generated in slug field with "-" in only admin page.but when I type same thing on add post page it won't generate slug automatically.
mycode
models.py
from django.db import models
from django.contrib.auth.models import User
from django_summernote.fields import SummernoteTextField
from django.urls import reverse
from django.template.defaultfilters import slugify
STATUS = (
(0,"Draft"),
(1,"Publish")
)
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
title_type = models.CharField(max_length=50, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')
updated_on = models.DateTimeField(auto_now= True)
content = SummernoteTextField(blank=True, null=True)
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
image = models.ImageField(upload_to='images',null=True, blank=True)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('home')
views.py
class AddPostView(CreateView):
model = Post
form_class = PostForm
template_name = 'add_post.html'
admin page
And add post page

The slug field should not be editable, remove the 'slug' field from the fields of AddPostView and of the Admin.
class AddPostView(CreateView):
model = Post
fields = ['title', 'title_type', 'author', 'updated_on', 'content',
'created_on', 'status', 'image']
form_class = PostForm
template_name = 'add_post.html'

Related

How do I display comments that are using a foreign key of another model in Django class based views?

I would like to list out the comments on my Post Detail page and wanted to see how I can connect a view to the specific comments for a given post?
Models.py
class Post(models.Model):
owner = models.ForeignKey(
Profile, null=True, blank=True, on_delete=models.SET_NULL)
title = models.CharField(max_length=200)
body = models.TextField()
Post_image = models.ImageField(
null=True, blank=True, default='default.jpeg')
create_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post', kwargs={'pk': self.pk})
class Meta:
ordering = ['-create_date']
class Comment(models.Model):
owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
text = models.TextField()
create_date = models.DateTimeField(auto_now_add=True)
Views.py
class PostDetailView(DetailView):
model = Post
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['comment_list'] = Post.comment_set.all()
return context
You can access the detail object of the DetailView with self.object:
class PostDetailView(DetailView):
model = Post
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['comment_list'] = self.object.comment_set.order_by('create_date')
return context

How to make autocomplete filter in django admin form with class based model

I want to add a dropdown with autocomplete filter such as select2 into django admin form with class based model. i have tried several tricks avilable over the internet but not succeeded. here are some code snippet i have. i want to show all category for a post which is already available into model.
in my model.py
class Post(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
featured_image = models.ImageField(null=True, blank=True, upload_to="blog/", verbose_name='Featured Image')
author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')
updated_on = models.DateTimeField(auto_now= True)
content = RichTextUploadingField()
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
class Meta:
ordering = ['-created_on', 'title']
def __str__(self):
return self.title
def _generate_slug(self):
value = self.title
slug_candidate = slugify(value, allow_unicode=True)
self.slug = slug_candidate
def save(self, *args, **kwargs):
if not self.pk:
self._generate_slug()
super().save(*args, **kwargs)
my admin.py
class PostAdmin(admin.ModelAdmin):
list_display = ('title', 'slug', 'status', 'category', 'author','created_on')
list_filter = ("status",)
search_fields = ['title', 'content']
prepopulated_fields = {'slug': ('title',)}
actions = [export_as_csv_action("CSV Export", fields=['title','slug','author','featured_image','status','created_on','updated_on'])]
how my form looks into django-admin
please suggest anything how to add i filter for category dropdown filter with autocomplete.
In Django 2.0+ you can just add autocomplete_fields to the ModelAdmin:
class PostAdmin(admin.ModelAdmin):
autocomplete_fields = ['category']
This will add asynchronous search of all categories the user has access to (versus a standard dropdown/select).

Django updateView saving another instance instead of updating

im trying to update my model but it just creates another instance and i cant figure out why. i was under the impression that all i needed was:
class QuestionUpdate(generic.UpdateView):
model = models.Question
form_class = QuestionForm
and it would take care of it for me but that doesnt seem to be the case.
im in django 1.11 and running python 3.6. Any and all help is appreciated.
models.py
class Question(models.Model):
class Meta:
ordering = ['-date_updated']
# user = models.ForeignKey(User, related_name="question", default='')
question = models.TextField(unique=False, blank=False, null=False)
question_html = models.TextField(blank=False, null=False)
answer = models.TextField(blank=False, null=False)
answer_html = models.TextField(blank=False,null=False)
date_created = models.DateTimeField(auto_now=True, null=True)
date_updated = models.DateTimeField(auto_now=True, null=True)
def __str__(self):
return self.question
# ^ to display an object in the Django admin site and
# as the value inserted into a template when it displays an object.
def save(self, *args, **kwargs):
self.question_html = misaka.html(self.question)
self.answer_html = misaka.html(self.answer)
super().save(*args, **kwargs)
views.py
class QuestionUpdate(generic.UpdateView):
model = models.Question
form_class = QuestionForm
# fields = ('question', 'answer')
def edit_question(self, request, id):
question = get_object_or_404(Question, id=id)
form = QuestionForm(request.POST, instance=question)
if form.is_valid():
form.save()
forms.py
class QuestionForm(forms.ModelForm):
# your_name = forms.CharField(label='Your name', max_length=100)
class Meta:
fields = ("question", 'answer')
model = models.Question
urls.py
url(r'questionupdate/(?P<pk>\d+)/$', views.QuestionUpdate.as_view(), name='update'),

Django NOT NULL constraint failed: shop_product.user_id

I am new to Django and I am trying to learn by practicing with some project but I am stuck with this problem,
NOT NULL constraint failed: shop_product.user_id
models.py
from django.db import models
from django.conf import settings
from django.core.urlresolvers import reverse
class Category(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='category_created')
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True, unique=True)
class Meta:
ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
class Product(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='product_created')
category = models.ForeignKey(Category, related_name='products')
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True)
image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.PositiveIntegerField()
available = models.BooleanField(default=True)
negiotiable = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
users_like = models.ManyToManyField(settings.AUTH_USER_MODEL,
related_name='product_liked',
blank=True)
class Meta:
ordering = ('name',)
index_together = (('id', 'slug'),)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('products_detail',
args=[self.slug])
Here is my views.py but am not sure if there is problem with my views and I think the problem will have to be with my models....
views.py
from django.views.generic import *
from django.core.urlresolvers import reverse_lazy
from .models import Category, Product
class CategoryList(ListView):
model = Category
class CategoryDetail(DetailView):
model = Category
class ProductList(ListView):
model = Product
class ProductDetail(DetailView):
model = Product
class ProductCreate(CreateView):
model = Product
fields = ("category", 'name', 'image', 'description', 'price', 'stock','available', 'negiotiable')
class ProductUpdate(UpdateView):
model = Product
fields = ('name', 'image', 'description', 'price', 'stock','available', 'negiotiable')
class ProductDelete(DeleteView):
model = Product
success_url = reverse_lazy('product_list')
Please let me know what could be done.
Either Add User into list:
class ProductCreate(CreateView):
model = Product
fields = ["category", 'name', 'image', 'description', 'price','stock','available', 'negiotiable', 'user']
OR make sure Field must be null=true and blank=True.
class Product(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='product_created', null=True, blank=True)
Add a form for your product,
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = "__all__"
Also, your user field must be null=True and blank=True.
Then in your create view,
class ProductCreate(CreateView):
model = Product
form_class = ProductForm
def form_valid(self, form):
form.instance.user = self.request.user
form.save()
return super(ProductCreate, self).form_valid(form)
Now, whenever a product is created, the user who created would be added as the user of the product.

IntegrityError in django rest framework

I'm playing with DRF and made a simple blog where anonymous people can comment on a blog post. I'm just using the browsable API at the moment, and everything seems to work fine until I try to post a comment. DELETE, GET, and PUT all work as expected, only POST.
The error I get is IntegrityError at /api/posts/i-had-a-blog-his-name-was-bingo/comments/: blog_comment.blogpost_id may not be NULL
I've searched thoroughly for an answer as to why this might be happening, but nothing is helping. Here's my code...
models.py
class BlogPost(models.Model):
created = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey('auth.User', related_name='posts')
title = models.CharField(max_length=100, unique=True)
content = models.TextField()
slug = models.SlugField(max_length=100, unique=True, editable=False)
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(BlogPost, self).save(*args, **kwargs)
#permalink
def get_absolute_url(self):
return ('post-detail', { 'slug': self.slug })
class Meta:
ordering = ('created',)
class Comment(models.Model):
created = models.DateTimeField(auto_now_add=True)
blogpost = models.ForeignKey(BlogPost, related_name='comments')
author = models.CharField(max_length=100, blank=False)
content = models.TextField()
class Meta:
ordering = ('created', 'author', 'content')
serializers.py
class CommentSerializer(serializers.HyperlinkedModelSerializer):
post = serializers.Field(source='blogpost.title')
class Meta:
model = Comment
fields = ('id', 'author', 'content', 'post')
class BlogPostSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.Field(source='owner.username')
url = serializers.HyperlinkedIdentityField(view_name='post-detail')
comments = serializers.HyperlinkedIdentityField(view_name='comment-list')
class Meta:
model = BlogPost
fields = ('url', 'id', 'title', 'content', 'owner', 'comments')
views.py
class CommentList(generics.ListCreateAPIView):
serializer_class = CommentSerializer
def get_queryset(self):
slug = self.kwargs['slug']
return Comment.objects.filter(blogpost__slug=slug)
class CommentDetail(generics.RetrieveUpdateDestroyAPIView):
serializer_class = CommentSerializer
permission_classes = (IsAdminOrNoEdit,)
def get_queryset(self):
slug = self.kwargs['slug']
return Comment.objects.filter(blogpost__slug=slug)
urls.py
commentpatterns = patterns('',
url(r'^$', views.CommentList.as_view(), name='comment-list'),
url(r'^(?P<pk>[0-9]+)/$', views.CommentDetail.as_view(), name='comment-detail'),
)
urlpatterns = patterns('blog.views',
url(r'^$', 'api_root'),
url(r'^posts/$', views.PostList.as_view(), name='post-list'),
url(r'^posts/(?P<slug>[-\w]+)/$', views.PostDetail.as_view(), name='post-detail'),
url(r'^posts/(?P<slug>[-\w]+)/comments/', include(commentpatterns)),
url(r'^users/$', views.UserList.as_view(), name='user-list'),
url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view(), name='user-detail'),
)
Any help would be greatly appreciated, this is driving me crazy.
Your Comment model defines a ForeignKey, which is not allowed to be null:
class Comment(models.Model):
...
blogpost = models.ForeignKey(BlogPost, related_name='comments')
...
which is ok, but your serializer does not include the blogpost id, so even if your request includes it, it will be just ignored. correct your serializer to include the blogpost field:
class CommentSerializer(serializers.HyperlinkedModelSerializer):
post = serializers.Field(source='blogpost.title')
blogpost = serializers.PrimaryKeyRelatedField()
class Meta:
model = Comment
fields = ('id', 'author', 'content', 'post', 'blogpost')
now when you create a post request, the blogpost field should contain the id of the blog post to which you're attaching this comment.

Categories

Resources