React unable to read property of undefined - reactjs

Can't figure out where my mistake is. Not able to map through to display the list of blog comments. I'm using django and react. From the code below, I tried to assess each blog post with comments. But I'm not able to get the comment property from the blog. If I do something like {blog.title} I get the title of the blog back on the browser. Since comments are associated with each post I try to get different properties of comment from the blog object (just as I specified in the code below) but the Value I'm getting is undefined. and have the following blog post and blog comment models.
class BlogComment(models.Model):
post = models.ForeignKey(BlogPost, on_delete=models.SET_NULL, related_name="post_comment", null=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name="user_comment", null=True)
name = models.CharField(max_length=200, null=True, blank=True)
comment = models.TextField(null=True, blank=True)
dateCreated = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.user.username)
class BlogPost(models.Model):
...
author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)
body = models.TextField()
dateCreated = models.DateTimeField(auto_now_add=True)
And the serializers for both models are:
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = BlogComment
fields = '__all__'
class BlogPostSerializer(serializers.ModelSerializer):
comments = serializers.SerializerMethodField(read_only=True)
class Meta:
model = BlogPost
fields = "__all__"
def get_comments(self, obj):
comments = obj.comment_set.all()
serializer = CommentSerializer(comments, many=True)
return serializer.data
<h2>{blog.title}</h2>
<img src={blog.image} />
<div variant='flush'>
{blog.comments.map((comment) => (
<div key={comment.id}>
<strong>{comment.name}</strong>
<p>{comment.dateCreated}</p>
<p>{comment.comment}</p>
</div>
))}
</div>
The comment API is functioning properly. In react, I'm able to add comments to each post using a form and the comments will appear in the database. But when I try to map through to display the comments of each blog post I get that error. How do I fix this?

You can check the length of an array before the map. Or you can use optional chaining.
like this obj?.property
<h2>{blog?.title}</h2>
<img src={blog?.image} />
<div variant='flush'>
{blog?.post?.comments.map((comment) => (
<div key={comment?.id}>
<strong>{comment?.name}</strong>
<p>{comment?.dateCreated}</p>
<p>{comment?.comment}</p>
</div>
))}
</div>

Related

Django Rest Framework: Form field populated with object representation after validation error

After the form is validated the field is populated with object representation from memory.
Form screenshot
I am using MoneyField in my Product model from django-money library.
models.py
class Product(models.Model):
CURRENCY_CHOICES = (
('EUR', 'EUR'),
('USD', 'USD'),
('GBP', 'GBP'),
('PLN', 'PLN')
)
price = MoneyField(max_digits=10, decimal_places=2, blank=False,
currency_choices=CURRENCY_CHOICES)
serializers.py
class ProductSerializer(serializers.ModelSerializer):
price_currency = serializers.ChoiceField(choices=Product.CURRENCY_CHOICES)
class Meta:
model = Product
fields = (
'price','price_currency',
)
views.py
class ProductList(generics.ListCreateAPIView):
serializer_class = ProductSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
queryset = Product.objects.all()
I would really appreciate any suggestions on why this is happening.

Unable to pass django model object to serializer

I am trying to pass a django model object to a field in a serializer that is for a foreign key field in the model. However, I get the error: "Object of type AuthorUser is not JSON serializable."
Here is the model the serializer is for:
class Article(models.Model):
title = models.CharField(max_length=200, unique=True)
author = models.ForeignKey(AuthorUser, on_delete=models.CASCADE)
body = models.TextField()
posted=models.BooleanField(default=False)
edited = models.BooleanField(default=False)
ready_for_edit = models.BooleanField(default=False)
Here is the serializer (author is the field specifically that is giving me trouble):
class CreateArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = ['title', 'body', 'author']
And here is the view that has the code that causes the error (the POST method is the part that causes the error):
#api_view(['GET', 'POST'])
def articles(request):
if request.method == 'GET':
articles = Article.objects.all()
serializer = CreateArticleSerializer(articles, many=True)
return Response(serializer.data)
if request.method == 'POST':
if request.user.is_authenticated:
author = AuthorUser.objects.get(id=request.data['author'])
request.data['author'] = author
print(request.data)
serializer = CreateArticleSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
else:
return HttpResponse(status=401)
Any help is appreciated! Just to let you know, when creating these articles using an id, it works, however, it creates a new field in Article called author_id. Then when I try to access author it gives me author_id so that doesn't work.
You need to change your serializer as follows:
class CreateArticleSerializer(serializers.ModelSerializer):
author = serializers.SlugRelatedField(queryset=AuthorUser.objects.all(),
slug_field='id')
class Meta:
model = Article
fields = ['title', 'body', 'author']
Now if you will pass id in your view while calling serializer it will create the object of model. Hope this will work for you.

Retrieving and Posting data from/to a related table in Django APIView

I am working on a Django application with two Models.
Messages - that contain twitter style messages
Feedback - response to messages including comments, likes, dislikes
I am writing APIView for Feedback, but it is not GETing or POSTing the relevant messages even though I can browse through the admin panel.
The code is as follows:
Models:
class Messages(models.Model):
postIdentifier = models.AutoField(primary_key=True)
title = models.CharField(max_length=100)
message = models.TextField(null=False)
class Feedback(models.Model):
isLiked = models.BooleanField(null=True)
isDisliked = models.BooleanField(null=True)
comment = models.TextField(null=True)
post = models.ForeignKey(Messages, on_delete=models.CASCADE)
Serializers:
class MessagesSerializer(serializers.ModelSerializer):
class Meta:
model = Messages
fields = ['postIdentifier', 'title', 'message']
class FeedbackSerializer(serializers.ModelSerializer):
message = MessagesSerializer()
class Meta:
model = Feedback
fields = ['isLiked', 'isDisliked', 'comment', 'post']
APIView for Feedback model
def get(self, request, id):
related_message_object = Messages.objects.filter(id)
feedback = Feedback.objects.filter('post'= related_message_object)
serializer = FeedbackSerializer(feedback)
return Response({
'data': serializer.data
})
def post(self, request, *args, **kwargs):
serializer = FeedbackSerializer(data= request.data)
if serializer.is_valid():
serializer.save()
return Response({
'message': 'Feedback data posted successfully!',
'data': serializer.data
})
The URLPattern for the feedback is
path('feedback/< id >/', FeedbackAPIView.as_view()),
#I am aware of spaces here on either side of id as I am unable to post the id with brackets on.
I am going through the rest_framework documentation, but I can not find relevant documentation with regard to the problem. Can anyone kindly point out my mistake in the get() method of FeedbackAPIView. I am hoping to achieve that when I browse feedback/2/ I want to see feedback relavant to Message with postIdentifier = 2. Any feedback is much appreciated!
As the feedback resource url is path('feedback/< id >/', FeedbackAPIView.as_view()),
then at def get(self, request, id): you should filter feedback by id :
feedback = Feedback.objects.filter(id=id).first()

How to show this blog django backend by its id in react frontend

models
class Blog(models.Model):
title = models.CharField(max_length=50)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
serializers
class BlogSerializer(serializers.ModelSerializer):
class Meta:
model = Blog
fields = '__all__'
views
class BlogDetailView(generics.RetrieveUpdateDestroyAPIView):
queryset = Blog.objects.all()
serializer_class = BlogSerializer
and urls
from django.urls import path
from .views import BlogDetailView
urlpatterns = [
path('blog/<int:pk>/', BlogDetailView.as_view()),
]
I'm trying to make a blog website. How can we show blogs by id in react js
I think you want to get list of blogs ordering by id. So, you can do like this-
views -
class BlogDetailView(generics.ListAPIView):
queryset = Blog.objects.all().order_by('-id') # descending order
serializer_class = BlogSerializer

can't get django views to filter objects by category (foreignkey attribute)

So, I have this class and would like to filter the list of quizzes according to categories (which is a foreignkey). I would like for the view to only display quizzes for each of the categories separately such as 'History', 'Chemistry' and so on.
class QuizListView(generic.ListView):
#model = Quiz
queryset = Quiz.objects.filter(Category='History')
Models:
class Quiz(models.Model):
title = models.CharField(
verbose_name=_("Titulli"),
max_length=60, blank=False)
description = models.TextField(
verbose_name=_("PĂ«rshkrimi"),
blank=True, help_text=_("a description of the quiz"))
url = models.SlugField(
max_length=60, blank=False,
help_text=_("a user friendly url"),
verbose_name=_("user friendly url"))
category = models.ForeignKey(
Category, null=True, blank=True,
verbose_name=_("Kategoria"), on_delete=models.CASCADE)
the category class:
class Category(models.Model):
category = models.CharField(
verbose_name=_("Category"),
max_length=250, blank=True,
unique=True, null=True)
objects = CategoryManager()
class Meta:
verbose_name = _("Kategori")
verbose_name_plural = _("Kategoritë")
def __str__(self):
return self.category
THis is the error on the terminal:
Cannot resolve keyword 'quiz_category' into field. Choices are: answers_at_end, categor
y, category_id, data_postimit, description, draft, exam_paper, fail_text, id, max_questions, pass_mark, question, random_o
rder, single_attempt, sitting, success_text, title, url
tried other ways but can't seem to figure it out, any help highly appreciated
category refers to a Category object, if you want to filter on the value of the category field of the related category object, you use double underscores (__), so:
class QuizListView(generic.ListView):
model = Quiz
queryset = Quiz.objects.filter(category__category='History')

Resources