Field 'id' expected a number but got '' in django - python

blog_id is not get. help me to solve this ---
models.py
class Blog(models.Model):
title = models.CharField(max_length=500)
body = models.TextField()
last_updated_on = models.DateTimeField(auto_now=True)
created_on = models.DateTimeField(auto_now_add=True)
author_instance = models.ForeignKey(AuthorInstance, on_delete=models.PROTECT)
status_draft = models.BooleanField(default=False, blank=True, null=True)
status_publish = models.BooleanField(default=False, blank=True, null=True)
likes = models.ManyToManyField(UserInstance, related_name='like', default=None, blank=True)
like_count = models.BigIntegerField(default='0')
def total_likes(self):
return self.likes.count()
views.py
def like_post(request):
post = get_object_or_404(Blog, id=request.POST.get('blog_id'))
how to solve????

views should be like
def like_post(request,id):
post = get_object_or_404(Blog, id=request.POST.get('blog_id'))

Related

Serializer for Recursive Comment in Django

models.py
class Comments(models.Model):
content = models.CharField(max_length=500)
sub_comment_id = models.ForeignKey('self', related_name='sub_comments', null=True, blank=True,
on_delete=models.CASCADE)
author_id = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='user_comments', on_delete=models.CASCADE)
article_id = models.ForeignKey(Article, related_name='article_comments', on_delete=models.CASCADE)
like = models.IntegerField(default=0)
dislike = models.IntegerField(default=0)
is_sub = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
def __str__(self):
return self.content
what can i do for showing all recursive comments in Comment Serializer?
i use django rest framework-recursive but does not work
I have never try something like this, but i don't see why it wouldn't work
CommentSerializer(serializers.Serializer):
content = serializers.CharField()
...
sub_comments = serializers.SerializerMethodField()
def get_sub_comments(self, comment):
return self.__class__(comment.sub_comments.all(), many=True).data

Signal so that when someone follows someone a thread is created between them 2

I have this in models and I want to create a signal that when someone follows someone, a thread is automatically created between that person and the person they followed. The models are in 2 different apps, one from the social network and the other from the chat.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.CharField(default='Hola, este es mi Blooby!!!', max_length=100)
image = models.ImageField(default='default.png')
def __str__(self):
return f'Perfil de {self.user.username}'
def following(self):
user_ids = Relationship.objects.filter(from_user=self.user)\
.values_list('to_user_id', flat=True)
return User.objects.filter(id__in=user_ids)
def followers(self):
user_ids = Relationship.objects.filter(to_user=self.user)\
.values_list('from_user_id', flat=True)
return User.objects.filter(id__in=user_ids)
class Post(models.Model):
timestamp = models.DateTimeField(default=timezone.now)
content = models.TextField(max_length=300)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')
liked = models.ManyToManyField(User, default=None, blank=True)
class Meta:
ordering = ['-timestamp']
def __str__(self):
return self.content
#property
def num_likes(self):
return self.liked.all().count()
LIKE_CHOICES = (
('Like', 'Like'),
('Unlike', 'Unlike'),
)
class Like(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
value = models.CharField(choices=LIKE_CHOICES ,default='Like', max_length=10)
class Relationship(models.Model):
from_user = models.ForeignKey(User, related_name='relationships', on_delete=models.CASCADE)
to_user = models.ForeignKey(User, related_name='related_to', on_delete=models.CASCADE)
def __str__(self):
return f'{self.from_user} to {self.to_user}'
class Comment(models.Model):
post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE)
name = models.ForeignKey(User,related_name="user_name" , on_delete=models.CASCADE)
body = models.TextField()
timestamp = models.DateTimeField(default=timezone.now)
The models of the app chat , here is the thread
class ThreadManager(models.Manager):
def by_user(self, **kwargs):
user = kwargs.get('user')
lookup = Q(first_person=user) | Q(second_person=user)
qs = self.get_queryset().filter(lookup).distinct()
return qs
class Thread(models.Model):
first_person = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='thread_first_person')
second_person = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True,
related_name='thread_second_person')
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
objects = ThreadManager()
class Meta:
unique_together = ['first_person', 'second_person']
class ChatMessage(models.Model):
thread = models.ForeignKey(Thread, null=True, blank=True, on_delete=models.CASCADE, related_name='chatmessage_thread')
user = models.ForeignKey(User, on_delete=models.CASCADE)
message = models.TextField()
timestamp = models.DateTimeField(default=timezone.now)

Django: How to check object category when using Model Inheritance?

Here is my models.py the idea of app is to have different objects (restaurants, services, etc) with different features (you can check each Model). But when I want to get all objecs Object.objects.all() I don't know which is the category for each of them.
models.py:
from django.db import models
from users.models import ProfileUser
from django.utils import timezone
# Create your models here.
class City(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return f"{self.name}"
class Object(models.Model):
author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE)
title = models.CharField(max_length=300)
city = models.ForeignKey(City, on_delete=models.CASCADE)
address = models.CharField(max_length=300)
phone = models.CharField(max_length=20, default='')
email = models.CharField(max_length=100, default='')
site = models.CharField(max_length=100, default='')
facebook = models.CharField(max_length=100, default='')
instagram = models.CharField(max_length=100, default='')
content = models.TextField()
rating = models.IntegerField(default=10)
created_date = models.DateTimeField(default=timezone.now)
approved_object = models.BooleanField(default=False)
admin_seen = models.BooleanField(default=False)
def __str__(self):
return f"{self.title}"
class Restaurant(Object):
seats = models.IntegerField()
bulgarian_kitchen = models.BooleanField(default=False)
italian_kitchen = models.BooleanField(default=False)
french_kitchen = models.BooleanField(default=False)
is_garden = models.BooleanField(default=False)
is_playground = models.BooleanField(default=False)
class SportFitness(Object):
is_fitness_trainer = models.BooleanField(default=False)
class CarService(Object):
is_parts_clients = models.BooleanField(default=False)
class BeautySalon(Object):
is_hair_salon = models.BooleanField(default=False)
is_laser_epilation = models.BooleanField(default=False)
class FastFood(Object):
is_pizza = models.BooleanField(default=False)
is_duner = models.BooleanField(default=False)
is_seats = models.BooleanField(default=False)
class CarWash(Object):
is_external_cleaning = models.BooleanField(default=False)
is_internal_cleaning = models.BooleanField(default=False)
is_engine_cleaning = models.BooleanField(default=False)
class Fun(Object):
is_working_weekend = models.BooleanField(default=False)
is_kids_suitable = models.BooleanField(default=False)
class Other(Object):
is_working_weekend = models.BooleanField(default=False)
class Comment(models.Model):
object = models.ForeignKey(Object, on_delete=models.CASCADE, related_name='comments')
author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE)
content = models.TextField()
rating = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return f"{self.content}"
You can not get the categories using the Object model.
Object class is created for a particular purpose:
it eliminates the need to declare certain characteristics of a class
Here you can use select_related or prefect_related to get the desired output.
OR
To fulfill your requirements you can use django-polymorphic for more detail you can refer the documentation.
This is how I did it:
Based on #wfehr commend and #Lokesh Pathak answer I implemented django-polymorphic, also added two additional rows(columns) to each model (only for Restaurants for now), so when foreach over all object I can print exact name of category, additional fields are
category_en_name = models.CharField(max_length=100, default='restaurants')
category_bg_name = models.CharField(max_length=100, default='Ресторант')
full models.py:
from django.db import models
from users.models import ProfileUser
from django.utils import timezone
from polymorphic.models import PolymorphicModel
# Create your models here.
class City(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return f"{self.name}"
class Object(PolymorphicModel):
author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE)
title = models.CharField(max_length=300)
city = models.ForeignKey(City, on_delete=models.CASCADE)
address = models.CharField(max_length=300)
phone = models.CharField(max_length=20, default='')
email = models.CharField(max_length=100, default='')
site = models.CharField(max_length=100, default='')
facebook = models.CharField(max_length=100, default='')
instagram = models.CharField(max_length=100, default='')
content = models.TextField()
rating = models.IntegerField(default=10)
created_date = models.DateTimeField(default=timezone.now)
approved_object = models.BooleanField(default=False)
admin_seen = models.BooleanField(default=False)
def __str__(self):
return f"{self.title}"
class Restaurant(Object):
seats = models.IntegerField()
bulgarian_kitchen = models.BooleanField(default=False)
italian_kitchen = models.BooleanField(default=False)
french_kitchen = models.BooleanField(default=False)
category_en_name = models.CharField(max_length=100, default='restaurants')
category_bg_name = models.CharField(max_length=100, default='Ресторант')
is_garden = models.BooleanField(default=False)
is_playground = models.BooleanField(default=False)
class SportFitness(Object):
is_fitness_trainer = models.BooleanField(default=False)
So I can take only Restaurants in views.py:
objects = Object.objects.instance_of(Restaurant)
And in template, I can show category name of each restaurant:
{% for object in objects %}
{{ object.category_bg_name }}
{% endfor %}

maximum recursion depth exceeded while calling a Python object, for counting views

I simply want to count the post pages being opened. so there's views field and update. but I get the following error. And I think it's better to put this logic in models.py not in views.py
models.py
class Post(models.Model):
withOutSub = 'WO'
withSub = 'WS'
WITH_OR_WITHOUT_SUB_CHOICES = [
(withOutSub, 'withoutsub'),
(withSub, 'withsub'),]
with_or_without_sub = models.CharField(
max_length=2,
choices=WITH_OR_WITHOUT_SUB_CHOICES,
default=withOutSub,
)
title = models.CharField(max_length=100)
content = models.TextField(blank=True, null=True)
embedded_content = models.TextField(blank=True, null=True)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
url = models.URLField(max_length=250, blank=True, null=True)
views = models.PositiveIntegerField(default=1)
likes = models.IntegerField(default=0)
rank_score = models.FloatField(default=0.0)
with_votes = PostVoteCountManager()
objects = models.Manager()
image = models.ImageField(upload_to='get_image_path_community', blank=True, null=True)
def update_view(self):
return self.views +1
self.save()
views = property(update_view)

Many to Many field Returning None django

When I try to print a field (Many-to-Many)in the terminal I only get the result "None". Am I missing something?
view.py
def assign_skill (request, pk):
plan = get_object_or_404(Plan, pk=pk)
if(request.GET.get('assign_skill')):
print("nummer1")
print(plan.title)
print(plan.skillonplan)
return redirect('all-plan')
models.py
class Plan(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, editable=False)
subscriber = models.ManyToManyField(User, blank = True, related_name = 'plansubscriber')
title = models.CharField(max_length=100, default = '', null=True, blank=True)
description = models.TextField(max_length=10000, default = '', null=True, blank=True)
company = models.CharField(max_length=200, null=True, editable=False)
created_date = models.DateTimeField(default=timezone.now)
skillonplan = models.ManyToManyField(Skill, null=True, blank = True, related_name='planneke')
duration = models.IntegerField(default=0,
validators=[MaxValueValidator(36), MinValueValidator(1)]
)
def get_skills(self):
return '\n'.join([p.skills for p in self.skill.all()])
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse_lazy('plan_detail', kwargs={'pk': self.id})
you can use following code, in order to return many to many fields :
print(plan.skillonplan.all())

Categories