I'm working on a small project using Django Rest Framework, I would like to access chatmessage_thread. I don't see chatmessage_thread in my result, should I add something in my serializer ?
This is my queryset:
class ThreadViewSet(viewsets.GenericViewSet):
queryset = Thread.objects.all()
serializer_class = ThreadSerializer
def list(self, request):
objectSerializer = self.serializer_class(Thread.objects.by_user(user=request.user).prefetch_related('chatmessage_thread').order_by('timestamp'), many=True)
return Response(objectSerializer.data)
This is my serializer:
from rest_framework import serializers
from chat.models import Thread
from datetime import date
class ThreadSerializer(serializers.ModelSerializer):
class Meta:
model = Thread
fields = '__all__'
depth = 1
should I add something to my Serializer?
This is my model:
from django.db import models
from django.contrib.auth import get_user_model
from django.db.models import Q
User = get_user_model()
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(auto_now_add=True)
I need help please
Yes you need to add a serializer for ChatMessage and add that as a field to ThreadSerializer. Something like this:
class ChatMessageSerializer(serializers.ModelSerializer):
class Meta:
model = ChatMessage
fields = '__all__'
class ThreadSerializer(serializers.ModelSerializer):
chatmessage_thread = ChatMessageSerializer(many=True)
class Meta:
model = Thread
fields = '__all__'
depth = 1
Related
Basically i want to authenticate the current user using user_details model and also to check if current user is a mentor and establish authorisation for the endpoints and preserve some endpoints from user
But i am not able to understand how to achieve it
my models.py
from django.db import models
# Create your models here.
class LiveClass(models.Model):
standard = models.IntegerField()
no_of_students_registered = models.IntegerField(default=0)
class Meta:
verbose_name_plural = 'Class'
class User_details(models.Model):
name = models.CharField(max_length=30)
standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE)
email = models.EmailField(max_length=30)
mobile_number = models.IntegerField()
class Meta:
verbose_name_plural = 'User_details'
class Mentor(models.Model):
name = models.CharField(max_length=30)
details = models.TextField()
class Meta:
verbose_name_plural = 'Mentors'
class LiveClass_details(models.Model):
standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE)
chapter_name = models.CharField(max_length=30)
chapter_details = models.TextField()
mentor_name = models.ForeignKey(Mentor, max_length=30, on_delete=models.CASCADE)
class_time = models.DateTimeField()
class Meta:
verbose_name_plural = 'LiveClass_details'
class LiveClass_registration(models.Model):
class_details = models.OneToOneField(LiveClass_details, on_delete=models.CASCADE)
name = models.OneToOneField(User_details, on_delete=models.CASCADE)
class Meta:
verbose_name_plural = 'LiveClass_registration'
my serializers.py
from rest_framework import serializers
from . import models
class LiveClass_serializer(serializers.ModelSerializer):
class Meta:
model = models.LiveClass
fields = '__all__'
class User_details_serializer(serializers.ModelSerializer):
class Meta:
model = models.User_details
fields = '__all__'
class LiveClass_details_serializer(serializers.ModelSerializer):
class Meta:
model = models.LiveClass_details
fields = '__all__'
class Mentor_serializer(serializers.ModelSerializer):
class Meta:
model = models.Mentor
fields = '__all__'
class LiveClass_registration_serializer(serializers.ModelSerializer):
class Meta:
model = models.LiveClass_registration
fields = '__all__'
my urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('liveclass_api.urls'))
]
my views.py
from django.shortcuts import render
from rest_framework import mixins
from rest_framework import generics
from . import serializers
from . import models
# Create your views here.
class ListLiveClass(mixins.ListModelMixin, generics.GenericAPIView):
queryset = models.LiveClass_details.objects.all()
serializer_class = serializers.LiveClass_details_serializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
class ListMentors(mixins.ListModelMixin, generics.GenericAPIView):
queryset = models.Mentor.objects.all()
serializer_class = serializers.Mentor_serializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
complete github code : https://github.com/dhruv354/django-liveclass.git
I can't add a new user using Django Rest Framework. Here is my code from models.py:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
password = models.CharField(max_length=15, default= None)
first_name = models.CharField(max_length=100, validators=[name_validator])
last_name = models.CharField(max_length=100, validators=[name_validator])
email = models.CharField(max_length=100, validators=[mail_validator])
created_at = models.DateTimeField(auto_now_add=True)
As you can see I am using models.OneToOneField cause I want to extend the default user to add some more fields.
Bellow is my serializers.py file:
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
permissions_classes = [
permissions.AllowAny
]
fields = '__all__'
The viewset is the following:
class UserViewset(viewsets.ModelViewSet):
queryset = Profile.objects.all()
serializer_class = ProfileSerializer
When I go to my endpoints and try to add a new user, I cannot put anything in the "user" field:
Click for image
I am a beginner and it would be of great help.
Thank you!
you can to this
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
password = models.CharField(max_length=15, default= None)
first_name = models.CharField(max_length=100, validators=[name_validator])
last_name = models.CharField(max_length=100, validators=[name_validator])
email = models.CharField(max_length=100, validators=[mail_validator])
created_at = models.DateTimeField(auto_now_add=True)
serializer.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = "__all__"
class ProfileSerializer(serializers.ModelSerializer):
user = UserSerializer(read_only=True)
class Meta:
model = Profile
fields = '__all__'
views.py
class UserViewset(viewsets.ModelViewSet):
queryset = Profile.objects.all()
serializer_class = ProfileSerializer
permission_classes = [permission. AllowAny,]
When you want to extend the default user to add some more fields, the best way for that is substituting a custom User model by inheritance the AbstractUser model. Using this way, you can CRUD the user easily.
Getting the wrong output when using DRF Filter, It returns data based on user_id only looks like it hasn't consider itemmaster_item_active status for the query.
Views.py
from django_filters.rest_framework import DjangoFilterBackend
class ItemmasterAPIView(mixins.CreateModelMixin, generics.ListAPIView):
serializer_class = ItemmasterSerializer
queryset = Itemmaster.objects.all()
filter_backends = [DjangoFilterBackend]
filter_class = ItemMasterItemFilter
Filters.py
from django_filters import rest_framework as filters
from itemmaster.models import Itemmaster, ItemmasterItem
class ItemMasterItemFilter(FilterSet):
user_id = filters.CharFilter('itemmaster_updated_by_id')
item_status = filters.BooleanFilter('itemmaster__itemmaster_item_active')
class Meta:
model = Itemmaster
fields = ('user_id', 'item_status',)
Serializers.py
class ItemmasterItemSerializer(serializers.ModelSerializer):
item_ref_image = serializers.SerializerMethodField(read_only=True)
class Meta:
model = ItemmasterItem
fields = ('item', 'itemmaster_item_active')
class ItemmasterSerializer(serializers.ModelSerializer):
itemmaster = ItemmasterItemSerializer(many=True, read_only=True)
class Meta:
model = Itemmaster
fields = ( 'itemmaster', 'itemmaster_updated_by')
models.py
itemmaster_updated_by = models.OneToOneField(
User, on_delete=models.CASCADE, related_name='itemmaster_updated_by')
class ItemmasterItem(models.Model):
itemmaster = models.ForeignKey(Itemmaster, on_delete=models.CASCADE, related_name='itemmaster')
itemmaster_item_active = models.BooleanField(default=True)
I have code where Product model has M2M field Comment model. I made methods in views.py for getting Product by id and all objects of Product, but there's problem with updating it. I can't fully understand how to update Product comments field. I already tried a lot of different answers and ideas, but nothing helps me. I'm using PUT method for update.
My main questions:
Where and how target Product id in order to update comments field in it?
After I find Product by it's id how I can update M2M field comments in it?
I tried:
Completely Lost: Many To Many with Serializers and Update in Django Rest Framework
Doesn't work at all, screams for 'collections.OrderedDict' object has no attribute 'id'
Django Rest update many to many by id
It's making PrimaryKeyRelatedField which is not correct for me.
How to update many to many Django REST?
Not enough information in answer, got stuck on it.
I read, but found no usefull information on my problem
products/models.py
from django.db import models
from comments.models import Comment
# Create your models here.
class Product(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=150, blank=True)
description = models.TextField(default="No description")
category = models.CharField(max_length=255, blank=True)
price = models.DecimalField(default=100, max_digits=15, decimal_places=2, blank=True)
photo_one = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, null=True)
photo_two = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, null=True)
photo_three = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, null=True)
photo_four = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, null=True)
is_popular = models.BooleanField(default=False)
is_hit = models.BooleanField(default=False)
has_sale = models.IntegerField(default=0)
comments = models.ManyToManyField(Comment, blank=True)
def __str__(self):
return self.name
comments/models.py
import uuid
from django.db import models
# Create your models here.
class Comment(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
username = models.CharField(max_length=255, default="default")
text = models.TextField()
rating = models.IntegerField()
def __string__(self):
return self.username
products/serializers.py
class ProductSerializer(serializers.ModelSerializer):
comments = CommentSerializer(many=True)
class Meta:
model = Product
fields = '__all__'
def update(self, instance, validated_data):
submitted_comments = validated_data.get('comments')
if submitted_comments:
for comment in submitted_comments:
comment_instance = Comment.objects.get(id=comment.id)
instance.children.add(comment_instance)
instance.save()
return instance
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = Comment
fields = ('id', 'username', 'text', 'rating')
products/views.py
import django_filters
from rest_framework import status
from rest_framework.generics import ListAPIView, RetrieveUpdateAPIView
from rest_framework.response import Response
from .models import Product
from .pagination import CustomPagination
from .serializers import ProductSerializer
class GetProductById(RetrieveUpdateAPIView):
serializer_class = ProductSerializer
filter_class = ProductFilter
queryset = Product.objects.all()
def get_product(self, pk):
try:
product = Product.objects.get(pk=pk)
except Product.DoesNotExist:
content = {
'status': 'Not Found'
}
return Response(content, status=status.HTTP_404_NOT_FOUND)
return product
def get(self, request, pk):
product = self.get_product(pk)
serializer = ProductSerializer(product)
return Response(serializer.data, status=status.HTTP_200_OK)
class ProductFilter(django_filters.FilterSet):
product_id = django_filters.UUIDFilter(name='id')
class Meta:
model = Product
fields = ['id']
class GetProducts(ListAPIView):
serializer_class = ProductSerializer
pagination_class = CustomPagination
def get_queryset(self):
products = Product.objects.all()
return products
def get(self, request):
products = self.get_queryset()
paginate_queryset = self.paginate_queryset(products)
serializer = self.serializer_class(paginate_queryset, many=True)
return self.get_paginated_response(serializer.data)
*products/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('api/products/', views.GetProducts.as_view(), name='get_products'),
path('api/product/<pk>/', views.GetProductById.as_view(), name='get_put_product')
]
I expect successful target by Product id and finding product.comments field
I expect successful adding new Comment to Product in it's comments field
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.