Django sitemap category page location not working - django

I made sitemap to my site but i have some problems.
First problem is end of the sitemap.xml page, lots of codes in it, but how can i remove these lines.
Here is my sitemap https://www.endustri.io/sitemap.xml
And here is the codes which i wanna remove...
And Second problem is
I have category page forexample: https://www.endustri.io/kategori/makine/
When i make sitemap class like this
class CategorySitemap(Sitemap):
changefreq = 'weekly'
priority = 0.8
def items(self):
return Category.objects.all()
def lastmod(self, obj):
return obj.date_added
In sitemap my category links be like this https://www.endustri.io/makine/ but it must be like this https://www.endustri.io/kategori/makine/
How can i fix this?
Here is my model.py
from django.db import models
from django.contrib.auth.models import User
from tinymce import models as tinymce_models
from django.urls import reverse
class Category(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField()
date_added = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural = 'Categories'
def __str__(self):
return str(self.title)
def get_absolute_url(self):
return reverse('detail', args=[str(self.slug)])
class Post(models.Model):
category = models.ForeignKey(Category, related_name="posts", on_delete=models.CASCADE)
title = models.CharField(max_length=300)
slug = models.SlugField(max_length=300)
intro = models.TextField()
body = tinymce_models.HTMLField()
description = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
featured_photo = models.ImageField(null=True, blank=True, upload_to="blog/")
date_added = models.DateTimeField(auto_now_add=True)
num_reads = models.PositiveIntegerField(default=0)
def __str__(self):
return str(self.title)
def get_absolute_url(self):
return reverse('detail', args=[str(self.slug)])
And sitemaps.py
from django.contrib.sitemaps import Sitemap
from .models import Post, Category
from django.urls import reverse
class PostSitemap(Sitemap):
changefreq = 'weekly'
priority = 0.9
def items(self):
return Post.objects.all().order_by('-id')
def lastmod(self, obj):
return obj.date_added
class CategorySitemap(Sitemap):
changefreq = 'weekly'
priority = 0.8
def items(self):
return Category.objects.all()
def lastmod(self, obj):
return obj.date_added

Related

Django Modelform user issues

I have a model form to list an item and I am trying to get the form to fill in the user id from the user that is submitting the form. Currently, the form is submitted successfully but it always uses the first user in the database's id for every item.
models.py
class Item(models.Model):
id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False )
creator = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, default=2)
item_name = models.CharField(max_length=40)
price = models.DecimalField(max_digits = 6, decimal_places=2)
description = models.CharField(max_length= 500)
main_image = models.ImageField(upload_to=path_and_rename , max_length=255, null=True, blank=True)
image_2 = models.ImageField(upload_to='items/', blank=True)
image_3= models.ImageField(upload_to='items/', blank=True)
image_4= models.ImageField(upload_to='items/', blank=True)
image_5= models.ImageField(upload_to='items/', blank=True)
quantity = models.IntegerField(default=1, validators=[ MaxValueValidator(100),MinValueValidator(1)])
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
def __str__(self):
return self.item_name
def get_absolute_url(self):
return reverse("item_detail_view", args=[str(self.id)])
forms.py
from django.forms import ModelForm, forms
from .models import Item
class List_Item_Form(ModelForm):
forms.ModelChoiceField(queryset=Item.objects.filter(user=user))
class Meta:
model = Item
def __init__(self, *args, **kwargs):
user = kwargs.pop("user", None)
super().__init__(*args, **kwargs)
views.py
class AddListing( generic.CreateView):
template_name = 'store/add_listing.html'
fields = ('item_name','price','description','main_image','quantity')
model = Item
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return super().form_valid(form)
It can be done using function based view too because there we get current user more easily.
Try this:
models.py
from django.db import models
from django.contrib.auth.models import User
class Item(models.Model):
creator = models.ForeignKey(User, on_delete=models.CASCADE)
item_name = models.CharField(max_length=40)
price = models.DecimalField(max_digits=6, decimal_places=2)
description = models.CharField(max_length=500)
main_image = models.ImageField(
upload_to=path_and_rename, max_length=255, null=True, blank=True)
image_2 = models.ImageField(upload_to='items/', blank=True)
image_3 = models.ImageField(upload_to='items/', blank=True)
image_4 = models.ImageField(upload_to='items/', blank=True)
image_5 = models.ImageField(upload_to='items/', blank=True)
quantity = models.PositiveIntegerField(default=1)
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
def __str__(self):
return self.item_name
admin.py
from django.contrib import admin
from home.models import Item
#admin.register(Item)
class ItemRegister(admin.ModelAdmin):
lis_display = ['id', 'creator', 'item_name', 'price', 'description']
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.list, name='home'),
path('success/', views.success, name='success')
]
forms.py
from django.forms import ModelForm, forms
from .models import Item
class ListItemForm(ModelForm):
class Meta:
model = Item
fields = ['item_name', 'price', 'main_image'
'description', 'quantity']
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .models import Item
from .forms import ListItemForm
def list(request):
if request.method == 'POST':
form = ListItemForm(request.POST)
if form.is_valid():
itemName = form.cleaned_data['item_name']
price = form.cleaned_data['price']
desc = form.cleaned_data['description']
quan = form.cleaned_data['quantity']
main_img = form.cleaned_data['main_image']
current_user = request.user
model_instance = Item(creator=current_user, item_name=itemName, price=price,
description=desc, quantity=quan, main_image=main_img)
model_instance.save()
return HttpResponseRedirect('/success/')
else:
form = ListItemForm()
return render(request, 'store/add_listing.html', {'form': form})
def success(request):
return render(request, 'store/success.html')
Rest of the fields of models you can customize very easily in the view.

Django Admin Shows Instance Created But Cannot See It In DRF View

I am following a course on DRF. It basically is creating a Q&A site. Now I tried answering a Question using the DRF interface.
But when I look at the question, it still shows answer count as zero.
But the answwers are visible on the Django Admin Panel.
My code for the same is:
models.py file
class Question(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
content = models.CharField(max_length=240)
slug = models.SlugField(max_length=240, unique=True)
author = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name="questions")
def __str__(self):
return self.content
class Answer(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
body = models.TextField()
question = models.ForeignKey(Question,
on_delete=models.CASCADE,
related_name="answers", null=True)
author = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
voters = models.ManyToManyField(settings.AUTH_USER_MODEL,
related_name='votes')
def __str__(self):
return f'{self.body} by {self.author.username}'
The serializers.py file:
from rest_framework import serializers
from ..models import (Answer, Question)
class AnswerSerializer(serializers.ModelSerializer):
author = serializers.StringRelatedField(read_only=True)
created_at = serializers.SerializerMethodField(read_only=True)
likes_count = serializers.SerializerMethodField(read_only=True)
user_has_voted = serializers.SerializerMethodField(read_only=True)
class Meta:
model = Answer
exclude = ['question', 'voters', 'updated_at']
def get_created_at(self, instance):
return instance.created_at.strftime("%B %d %y")
def get_likes_count(self, instance):
return instance.voters.count()
def get_user_has_voted(self, instance):
request = self.context.get('request')
return instance.voters.filter(pk=request.user.pk).exists()
class QuestionSerializer(serializers.ModelSerializer):
author = serializers.StringRelatedField(read_only=True)
created_at = serializers.SerializerMethodField(read_only=True)
slug = serializers.SlugField(read_only=True)
answers_count = serializers.SerializerMethodField(read_only=True)
user_has_answered = serializers.SerializerMethodField(read_only=True)
class Meta:
model = Question
exclude = ['updated_at']
def get_created_at(self, instance):
return instance.created_at.strftime("%B %d %y")
def get_answers_count(self, instance):
return instance.answers.count()
def get_user_has_answered(self, instance):
request = self.context.get('request')
return instance.answers.filter(author=request.user.pk).exists()
And the views.py file
from rest_framework import generics, viewsets
from rest_framework.generics import get_object_or_404
from rest_framework.exceptions import ValidationError
from rest_framework.permissions import IsAuthenticated
from ..models import Question, Answer
from .serializers import QuestionSerializer, AnswerSerializer
from .permissions import IsAuthorOrReadOnly
class QuestionViewSet(viewsets.ModelViewSet):
queryset = Question.objects.all()
lookup_field = 'slug'
serializer_class = QuestionSerializer
permissions_class = [IsAuthorOrReadOnly, IsAuthenticated]
def perform_create(self, serializer):
serializer.save(author=self.request.user)
class AnswerCreateAPIView(generics.CreateAPIView):
queryset = Answer.objects.all()
serializer_class = AnswerSerializer
permission_classes = [IsAuthenticated]
def perform_create(self, serializer):
request_user = self.request.user
kwarg_slug = self.kwargs.get("slug")
question = get_object_or_404(Question, slug=kwarg_slug)
if question.answers.filter(author=request_user).exists():
raise ValidationError('You Have Already Answered')
serializer.save(author=self.request.user)
You need provide question for the creation of answer explicitly if you exlcude product in your AnswerSerializer
class AnswerCreateAPIView(generics.CreateAPIView):
...
def perform_create(self, serializer):
...
serializer.save(author=self.request.user, question=question)

OperationalError at /admin/blogapp/post/220/change/ no such table: blogapp_post_likes?

I've made a django blog app and its working fine. Now I'm trying to add a like feature to the blogs by the users.
I added a likes field in my Post model but as soon as I ran the makemigrations and migrations command and went into my django-admin and click on the Post model, I got this -no such table: blogapp_post_likes.
I'm learning from this tutorial and he also did the same thing but his migrations worked.
I've tried deleting the migrations folder from the project prior to the makemigrations and migration command but its not working.
Here's my models.py file-
from django.db import models
from django.urls import reverse
from django.utils import timezone
from django.contrib.auth.models import User
from datetime import datetime, timedelta
from PIL import Image
class Profile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
contact = models.CharField(max_length=12,blank=True)
image = models.ImageField(upload_to='profile_pictures', default='default.png')
description = models.CharField(max_length=100,blank=True,null=True)
def __str__(self):
return f'{self.user.username}'
class Post(models.Model):
author = models.ForeignKey(User,on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
create_date = models.DateTimeField(auto_now_add=True)
published_date = models.DateTimeField(blank=True)
likes = models.ManyToManyField(User,related_name='post_likes',blank=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def approve_comments(self):
return self.comments.filter(approved_comment=True)
def get_absolute_url(self):
return reverse('blogapp:post_detail',kwargs={'pk':self.pk})
def __str__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
author = models.CharField(max_length=100)
text = models.TextField(max_length=264)
created_date = models.DateTimeField(default=timezone.now)
approved_comment = models.BooleanField(default=False)
def approve(self):
self.approved_comment = True
self.save()
def get_absolute_url(self):
return reverse('blogapp:post_list')
def __str__(self):
return self.text
Can anyone help?

I cannot see Cathegory list admin, How to fix that

I registred Category admin in models.py. I added that model in Post model via ForenKey. But when i log into admin console i cannot see my Categories, I just see Category Object(1), Category Object(2) and so on.
I will provide you a print screen and a code.
http://prntscr.com/nxt25y
instead if Japanese Kitchen or any other category (im working blog for chef),
i see Category Object, the one that i highlighted on printscreen.
I think its not a big deal but i didnt worked on django for quite some time so i forgot a lot.
Can you spot a mistake?
Thanks guys
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
from django.utils.text import slugify
from ckeditor_uploader.fields import RichTextUploadingField
class Category(models.Model):
name = models.CharField(max_length=150)
slug = models.SlugField(max_length=150)
class Meta:
ordering = ('name',)
verbose_name = 'catergory'
verbose_name_plural = 'catergories'
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(
help_text="A short label, generally used in URLs.", default='', max_length=100)
category = models.ForeignKey(
Category, on_delete=models.CASCADE, default='New category')
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
content = RichTextUploadingField(blank=True, null=True)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
ordering = ['-date_posted']
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('detail', kwargs={'slug': self.slug})
def __str__(self):
return self.title
this is admin.py
from .models import Post, Category
from django.forms import ModelForm
from django.contrib.admin import ModelAdmin
from suit_ckeditor.widgets import CKEditorWidget
class PostForm(ModelForm):
class Meta:
widgets = {
'name': CKEditorWidget(editor_options={'startupFocus': True})
}
class CategoryAdmin(admin.ModelAdmin):
list_display = ('name', 'slug')
prepopulated_fields = {'slug': ('name',)}
admin.site.register(Category, CategoryAdmin)
class PostAdmin(admin.ModelAdmin):
form = PostForm
list_display = ['title', 'slug', 'date_posted', 'author']
list_filter = ['title', 'date_posted']
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Post, PostAdmin)
You need to override __str__ method in your models to handle what you intend to display on admin.
class Category(models.Model):
name = models.CharField(max_length=150)
slug = models.SlugField(max_length=150)
class Meta:
ordering = ('name',)
verbose_name = 'catergory'
verbose_name_plural = 'catergories'
def __str__(self):
return self.name

ContentType Issue -- Human is an idiot - Can't figure out how to tie the original model to a ContentType abstracted 'Favorite' model

Originally started here: Django IN query as a string result - invalid literal for int() with base 10
I have a number of apps within my site, currently working with a simple "Blog" app. I have developed a 'Favorite' app, easily enough, that leverages the ContentType framework in Django to allow me to have a 'favorite' of any type... trying to go the other way, however, I don't know what I'm doing, and can't find any examples for.
I'll start off with the favorite model:
favorite/models.py
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.contrib.auth.models import User
class Favorite(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
user = models.ForeignKey(User)
content_object = generic.GenericForeignKey()
class Admin:
list_display = ('key', 'id', 'user')
class Meta:
unique_together = ("content_type", "object_id", "user")
Now, that allows me to loop through the favorites (on a user's "favorites" page, for example) and get the associated blog objects via {{ favorite.content_object.title }}.
What I want now, and can't figure out, is what I need to do to the blog model to allow me to have some tether to the favorite (so when it is displayed in a list it can be highlighted, for example).
Here is the blog model:
blog/models.py
from django.db import models
from django.db.models import permalink
from django.template.defaultfilters import slugify
from category.models import Category
from section.models import Section
from favorite.models import Favorite
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
class Blog(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=140, editable=False)
author = models.ForeignKey(User)
homepage = models.URLField()
feed = models.URLField()
description = models.TextField()
page_views = models.IntegerField(null=True, blank=True, default=0 )
created_on = models.DateTimeField(auto_now_add = True)
updated_on = models.DateTimeField(auto_now = True)
def __unicode__(self):
return self.title
#models.permalink
def get_absolute_url(self):
return ('blog.views.show', [str(self.slug)])
def save(self, *args, **kwargs):
if not self.slug:
slug = slugify(self.title)
duplicate_count = Blog.objects.filter(slug__startswith = slug).count()
if duplicate_count:
slug = slug + str(duplicate_count)
self.slug = slug
super(Blog, self).save(*args, **kwargs)
class Entry(models.Model):
blog = models.ForeignKey('Blog')
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=140, editable=False)
description = models.TextField()
url = models.URLField(unique=True)
image = models.URLField(blank=True, null=True)
created_on = models.DateTimeField(auto_now_add = True)
def __unicode__(self):
return self.title
def save(self, *args, **kwargs):
if not self.slug:
slug = slugify(self.title)
duplicate_count = Entry.objects.filter(slug__startswith = slug).count()
if duplicate_count:
slug = slug + str(duplicate_count)
self.slug = slug
super(Entry, self).save(*args, **kwargs)
class Meta:
verbose_name = "Entry"
verbose_name_plural = "Entries"
Any guidance?
The django doc on it is here: Reverse generic relations. Basically on the Blog model itself you can add a GenericRelation...
class Blog(models.Model):
favorites = generic.GenericRelation(Favorite)
For a given blog you can find all of the Favorite models that are associated with it...
b = Blog.objects.get(slug='hello-world-blog-slug')
all_blog_favorites = b.favorites.objects.all()
Or see if the current user has the blog favorited...
user_has_blog_favorited = b.favorites.objects.filter(user=request.user).exists()