Not getting foreign key data in django api views - django

Currently I have a site, and I want the user to be able to view their liked articles. I want this to be included in the user api view that is already set up. I have tried the tracks = serializers.StringRelatedField(many=True)that is in the drf docs yet this didn't work. I have also tried the following:
from rest_framework import serializers
from articles.models import Article, CustomUser,FavoriteArticles
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = ('title', 'content')
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = CustomUser
fields = '__all__'
class FavoriteArticleSerializer(serializers.ModelSerializer):
class Meta:
model = FavoriteArticles
fields = '__all__'
class UserProfileSerializer(serializers.ModelSerializer):
fav_title = FavoriteArticleSerializer(read_only=False)
class Meta:
model = CustomUser
fields = 'username, git, email, fav_article, fav_title, homepage'
and my models:
from django.db import models
# users/models.py
from django.contrib.auth.models import AbstractUser
from django.db.models.signals import post_save
from django.dispatch import receiver
import uuid
class ProgrammingLanguage(models.Model):
programming_language = models.CharField(max_length=120, null=False, primary_key=True, default="React")
def __str__(self):
return self.programming_language
class Article(models.Model):
title = models.CharField(max_length=25, primary_key=True)
content = models.TextField()
usedfor = models.TextField()
url=models.CharField(max_length=200, null=True)
article_programming_language = models.ForeignKey(ProgrammingLanguage, on_delete=models.CASCADE, related_name="article_programming_language", default="react")
score = models.IntegerField(max_length=5, null=0)
def __str__(self):
return self.title
class CustomUser(AbstractUser):
username = models.CharField(max_length=50, unique=True, primary_key=True)
git = models.CharField(max_length=200, null=True)
homepage = models.CharField(max_length=250, null=True)
user_programming_language = models.ForeignKey(ProgrammingLanguage, on_delete=models.CASCADE, related_name="most_used_programming_language", default="react")
def __str__(self):
return str(self.username)
class FavoriteArticles(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
fav_title = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='fav_title')
reasons_liked = models.CharField(max_length=120, null=True)
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name="user", default="tom" )
def __unicode__(self):
return '%s: %s' % (self.fav_title, self.reasons_liked)

I think you misunderstood what related_name means. It specifies how you would access a model from its reverse relationship. So I'd recommend you remove it from fields in your FavoriteArticles model and use the default Django already provides (in this case favoritearticles_set):
class FavoriteArticles(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
fav_title = models.ForeignKey(Article, on_delete=models.CASCADE)
reasons_liked = models.CharField(max_length=120, null=True)
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, default="tom")
def __unicode__(self):
return '%s: %s' % (self.fav_title, self.reasons_liked)
This way, you can access favorite articles of a user via my_user.favoritearticles_set.all(). Then, you can change your UserSerializer to include a liked_articles field which is populated from the favoritearticles_set reverse relationship to a user's FavoriteArticles using a source attribute:
class UserSerializer(serializers.ModelSerializer):
liked_articles = FavoriteArticleSerializer(source='favoritearticles_set', many=True, read_only=True)
class Meta:
model = CustomUser
# explicitly include other fields as required
fields = ('username', 'git', 'user_programming_language', 'liked_articles')
Note that we've made this a read_only field, so it will only get populated if you perform a GET request.

Related

how to save multiple objects to the database in django rest framework views

so what i'm trying to do is add a new product to my data base using django's restapi
but a product may contain multiple categories which are related throught a third many to many
model and extra pictures which are ForeignKeyed to the product
this is my models.py
class Products(models.Model):
product_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=35, null=False, unique=True)
description = models.CharField(max_length=255)
price = models.DecimalField(max_digits=10, decimal_places=2, default=0.)
main_image = models.FileField(upload_to='shop/images')
created_on = models.DateTimeField(blank=True, default=datetime.now)
class Category(models.Model):
category_id = models.AutoField(primary_key=True)
category = models.CharField(max_length=20, null=True, blank=True)
created_on = models.DateTimeField(blank=True, default=datetime.now)
class Meta:
db_table = 'Category'
class ProductsCategory(models.Model):
productscategory_id = models.AutoField(primary_key=True)
category = models.ForeignKey(to=Category, on_delete=models.CASCADE)
product = models.ForeignKey(to=Products, on_delete=models.CASCADE)
created_on = models.DateTimeField(blank=True, default=datetime.now)
class Meta:
db_table = 'ProductsCategory'
class Pictures(models.Model):
picture_id = models.AutoField(primary_key=True)
image = models.FileField(upload_to='shop/images')
product = models.ForeignKey(to=Products, on_delete=models.CASCADE)
created_on = models.DateTimeField(blank=True, default=datetime.now)
class Meta:
db_table = 'Pictures'
and heres what i've tryed:
#api_view(['POST'])
#permission_classes([IsModerator])
def create_product(request):
product_details = ProductsSerializer(request.POST, request.FILES)
pictures = PicturesSerializer(request.POST, request.FILES, many=True)
category_list = request.POST.getlist("category")
if product_details.is_valid() and validate_file_extension(request.FILES.get("main_image")):
try:
product = product_details.save()
if len(category_list) > 0:
for i in category_list:
category = Category.objects.get(category=i)
ProductsCategory.objects.create(category=category, product=product)
if pictures:
for image in request.FILES.getlist("image"):
if validate_file_extension(image):
Pictures.objects.create(image=image, product=product)
else:
error = {"error": "invalid extra pictures extension"}
return Response(error)
return Response((product_details.data, pictures.data, category_list), status=status.HTTP_201_CREATED)
except Exception as e:
return Response(e)
else:
return Response((product_details._errors, pictures._errors), status=status.HTTP_400_BAD_REQUEST)
and the output:
result
how am i supposed to use this content input?
or if you know a better for my main question of saving multiple models in the database and their relationships please leave an answer, thanks in advance
I suggest you change your models.py structure to this:
from django.db import models
class Category(models.Model):
category = models.CharField(max_length=20, null=True, blank=True)
created_on = models.DateTimeField(auto_now=True)
class Meta:
verbose_name_plural = "Categories"
class Picture(models.Model):
image = models.FileField(upload_to='shop/images')
product = models.ForeignKey(to=Products, on_delete=models.CASCADE)
created_on = models.DateTimeField(blank=True, default=datetime.now)
class Product(models.Model):
name = models.CharField(max_length=35, null=False, unique=True)
description = models.CharField(max_length=255)
price = models.DecimalField(max_digits=10, decimal_places=2, default=0.)
main_image = models.FileField(upload_to='shop/images')
more_images = models.ManyToManyField(Pictures, on_delete=models.CASCADE)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
created_on = models.DateTimeField(auto_now=True)
Then in your serializer.py add:
from rest_framework import serializers
from .models import Category, Picture, Product
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = "__all__"
class PictureSerializer(serializers.ModelSerializer):
class Meta:
model = Picture
fields = "__all__"
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = "__all__"
In your views, I suggest you use ViewSets:
views.py
from .models import Category, Picture, Product
from .serializer import CategorySerializer, PictureSerializer, ProductSerializer
from rest_framework import viewsets
# import custom permissions if any
class CategoryViewSet(viewsets.ModelViewSet):
serializer_class = CategorySerializer
queryset = Category.objects.all()
class PictureViewSet(viewsets.ModelViewSet):
serializer_class = PictureSerializer
queryset = Picture.objects.all()
class ProductViewSet(viewsets.ModelViewSet):
serializer_class = ProductSerializer
queryset = Product.objects.all()
permission_classes = [IsModerator]
In your app's urls.py, add the router for your viewsets and it will create the paths for your views automatically:
from django.urls import path
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'category', views.CategoryViewSet, basename='category')
router.register(r'picture', views.PictureViewSet, basename='picture')
router.register(r'product', views.ProductViewSet, basename='product')
urlpatterns = [
path('', include(router.urls)),
]
Changes log:
You do not need to add an ID field to every model, Django does that for you. Unless it's a particular case.
Your database tables are named after your model by default. So no need to specify that too.
I simplified your models' structure to make it cleaner. But it still does what you want it to do.
Django adds an s to create a plural name for every model. So you can name it in singular form unless needed to specify. eg. categories.
The viewsets will reduce your work by providing you with listing and retrieval actions.
To access a specific instance of eg. a product, you will just add a /<product id> after the product listing and creation endpoint.
Note: You have to add the id without the brackets.
I also suggest you go through this DRF tutorial. It will improve your understanding of Django REST framework.

How to display all child category from parent category in django-rest-framework

I'm trying to show my all children category from parent category. I want to just hit one API end and show all tables which is related to that item. I want to hit "Master-Category" and show all releated "Category","Sub-Category" and "Root-Item" in Hierarchy form. I display all the data but cannot in Hierarchy form. Can anyone please give me the solution for this problem.
Model.py
from django.db import models
from django.contrib.auth.models import User
class MasterCategory(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True,
verbose_name="Created By")
title = models.CharField(max_length=100, null=False, blank=False)
description = models.TextField(default='')
def __str__(self):
return str(self.title)
#property
def category(self):
data = NewCategory.objects.filter(master_category__id=self.id).values
return data
#property
def sub_category(self):
data = NewSubcategory.objects.filter(category__id=self.id).values
return data
#property
def root_item(self):
data = Rootitem.objects.filter(sub_category__id=self.id).values
return data
class NewCategory(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True,
verbose_name="Created By")
title = models.CharField(max_length=100, null=False, blank=False)
description = models.TextField(default="")
master_category = models.ForeignKey(
MasterCategory, on_delete=models.CASCADE, null=True, blank=True)
def __str__(self):
return str(self.title)
class NewSubcategory(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True,
verbose_name="Created By")
title = models.CharField(max_length=100, null=False, blank=False)
description = models.TextField(default="")
category = models.ForeignKey(NewCategory, on_delete=models.CASCADE, null=True,
blank=True)
def __str__(self):
return str(self.title)
class Rootitem(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True,
verbose_name="Created By")
title = models.CharField(max_length=100, null=False, blank=False)
description = models.TextField(default="")
sub_category = models.ForeignKey(NewSubcategory, on_delete=models.CASCADE,
null=True, blank=True)
def __str__(self):
return str(self.title)
Serializers.py
I add #property function name in MasterCategorySerializer fields, "category", "sub_category", "root_item"
from .models import MasterCategory, NewCategory, NewSubcategory, Rootitem
from rest_framework import serializers
class MasterCategorySerializer(serializers.ModelSerializer):
class Meta:
model = MasterCategory
fields = ["title", 'category', 'sub_category', 'root_item']
class NewCategorySerializer(serializers.ModelSerializer):
class Meta:
model = NewCategory
fields = "__all__"
class NewSubcategorySerializer(serializers.ModelSerializer):
new_cat = NewCategorySerializer(source='category',read_only=True, many=True)
class Meta:
model = NewSubcategory
fields = "__all__"
class RootitemSerializer(serializers.ModelSerializer):
class Meta:
model = Rootitem
fields = "__all__"
**Viewset.py**
from API_app.models import MasterCategory
from API_app.serializers import MasterCategorySerializer
from rest_framework import viewsets
class MasterCategoryViewSet(viewsets.ModelViewSet):
queryset = MasterCategory.objects.all()
serializer_class = MasterCategorySerializer
My Desired Output, what i want.
{
Electronics <---- Master-Category
{
Smart-Phone <---- Category
{
Samsung <---- Sub-Category
{
Samsung S20 Ultra <---- Root-Item
}
}
}
}
Change your serializers as below. For this nested structure you don't need properties. As tables are connected with foreign key you can define related name between models and assign to its serializer. Default related name between table is tablename_set.
class RootitemSerializer(serializers.ModelSerializer):
class Meta:
model = Rootitem
fields = "__all__"
class NewSubcategorySerializer(serializers.ModelSerializer):
rootitem_set = RootitemSerializer(many=True)
class Meta:
model = NewSubcategory
fields = "__all__"
class NewCategorySerializer(serializers.ModelSerializer):
newsubcategory_set = NewSubcategorySerializer(many=True)
class Meta:
model = NewCategory
fields = "__all__"
class MasterCategorySerializer(serializers.ModelSerializer):
newcategory_set = NewCategorySerializer(many=True)
class Meta:
model = MasterCategory
fields = "__all__"
We have relationship between MasterCategory and NewCategory. As you don't define related_name therefore related name is newcategory_set and its response is NewCategorySeralizer. Make many=True because they are related with foreign key as there can be multiple newcategory related to mastercategory. Other relations are same as above explanation.
If you want to change this default related name then look at related_name, you can define it inside models.ForeignKey()

Django how to reverse to autocreated page

I have a CustomUser model and a UserProfile model. The UserProfile is linked to the CustomUser via a foreign key. A new UserProfile is auto created whenever a new CustomUser is created.
After a new CustomUser is added, I want to land on the UserProfile page so the person adding the user can also edit the profile. I have not been able to figure out how to specify the UserProfile id in the view for adding the new user.
The models:
class UserProfile(models.Model):
user = models.OneToOneField(CustomUser, null=True, on_delete=models.CASCADE)
preferred_name = models.CharField(null=True, blank=True, max_length= 75)
pronouns = models.CharField(null=True, blank=True, max_length= 40)
phone = PhoneField(blank=True, help_text='Contact phone number')
job_title = models.CharField(null=True, blank=True, max_length= 75)
birthdate = models.DateField(null=True, blank=True)
bio = tinymce_models.HTMLField(null=True, blank=True)
profile_image = ConstrainedFileField(
null=True,
blank=True,
upload_to='projects/employee_profiles',
content_types=['image/png', 'image/jpg', 'image/jpeg', 'image/gif'],
max_upload_size=2097152,
)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=CustomUser)
class CustomUser(AbstractUser):
full_name = models.CharField(max_length=250, null=True)
age = models.PositiveIntegerField(null=True, blank=True)
employee_type = models.ForeignKey(Group, null=True, on_delete=models.SET_NULL, default=1)
is_active = models.BooleanField(null=False, default=True)
The view:
class AddCompanyEmployee(CreateView):
model = CustomUser
template_name = 'manage/add_employee.html'
form_class = AddCompanyEmployeeForm
def get_success_url(self):
return reverse('userprofile_detail', args=[self.kwargs.get('userprofile_pk')])
The form:
class AddCompanyEmployeeForm(UserCreationForm):
class Meta:
model = CustomUser
fields = UserCreationForm.Meta.fields + ('email', 'full_name', 'age',)
The UserProfile URL:
from django.urls import path
from .views import EmployeeDirectory, UserProfileDetailView
urlpatterns = [
path('', EmployeeDirectory.as_view(), name='directory'),
path('profile/<int:pk>', UserProfileDetailView.as_view(), name='userprofile_detail'),
]
This is the error I get when I add a new user:
NoReverseMatch at /manage/add_employee/
Reverse for 'userprofile_detail' with arguments '(None,)' not found. 2 pattern(s) tried: ['user\\-profiles/profile/(?P<pk>[0-9]+)\\Z', 'directory/profile/(?P<pk>[0-9]+)\\Z']
You can work with:
class AddCompanyEmployee(CreateView):
model = CustomUser
template_name = 'manage/add_employee.html'
form_class = AddCompanyEmployeeForm
def get_success_url(self):
return reverse(
'userprofile_detail', kwargs={'pk': self.object.userprofile.pk}
)
It will look for the OneToOneField in reverse, and thus obtain the .pk of the related UserProfile.
That being said it is quite strange that you use both a CustomUser and UserProfile. Usually if you implement your own user model, that is to add fields that you would otherwise store in a UserProfile, and thus to prevent having to work with two models.

Recording user activity in django?

I have a project in which some user can perform CRUD activities. I want to record who did what and when. Currently, I am thinking of making a model
class UserAction(models.Model):
user_id = models.CharField(max_length=100)
action_flag = models.CharField(max_length=100)
class_id = models.CharField(max_length=100)
action_taken_at = models.DateTimeField(default=datetime.now())
and making a function that fills my UserAction table. Is there any better way to do this?
app/models.py:
from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
class Action(models.Model):
sender = models.ForeignKey(User,related_name='user',on_delete=models.CASCADE)
verb = models.CharField(max_length=255)
target_ct = models.ForeignKey(ContentType, blank=True, null=True,
related_name='target_obj', on_delete=models.CASCADE)
target_id = models.PositiveIntegerField(null=True, blank=True)
target = GenericForeignKey('target_ct', 'target_id')
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('-created',)
def __str__(self):
return self.pk
app/admin.py
from .models import Action
admin.site.register(Action)
How you can use it ?
you can now import this models(Action) inside any of yours views.py.
Example if you have a post and a user likes it.you can just write
Action.objects.create(sender=request.user,verb="likes this post",target=post)
and now when you look at your admin you will see that tartget_id=post.pk
Here I assume that a user is authenticated and you can change it for your own.Happy coding!!!
You can do it by creating a model in
Models.py
class Auditable(models.Model):
ip = models.GenericIPAddressField(null=True)
user_agent = models.CharField(max_length=255, blank=True)
remote_host = models.CharField(max_length=255, blank=True)
created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name="%(app_label)s_%(class)s_created_by", null=True, blank=True) # this is for web user
modified_at = models.DateTimeField(auto_now=True, blank=True, null=True)
modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name="%(app_label)s_%(class)s_modified_by", null=True, blank=True) # this is for web user
class Meta:
abstract = True
def get_fields(self):
list_fields = ['ip', 'user_agent',
'remote_host', 'created_by', 'modified_by']
return [(field.verbose_name, field._get_val_from_obj(self)) for field in self.__class__._meta.fields if field.name not in list_fields and not
(field.get_internal_type() == "DateTimeField" and
(field.auto_now is True or field.auto_now_add is True)) and
field.concrete and (not field.is_relation or field.one_to_one or
(field.many_to_one and field.related_model))]
You can give any class name (i have given auditable). So all you have to do is pass this class (auditable) in your every model instead of models.Model
For Eg:
class Student(Auditable):
By doing this it will add all the auditable fields records in every table you have created.
Hope you may get your answer by doing this.

Django Rest - Cant serialize items

I'm trying to serialize nested relations, but got an error during create model from request: 'MeasureUnit' object has no attribute 'unit'
What am I doing wrong? I'm just trying to create model MeasureItem, but got error in MeasureUnit somehow.
My models:
from django.db import models
from measure_unit.models import MeasureUnit
from main_user.models import MainUser
class Item(models.Model):
code = models.CharField(unique=True, max_length=15)
current_code = models.CharField(blank=True, null=True, max_length=15)
title = models.CharField(default='', max_length=100)
description = models.TextField(blank=True, null=True)
measure_units = models.ManyToManyField(MeasureUnit, through='MeasureItem', through_fields=('item', 'unit'), blank=True)
class Meta:
ordering = ('created_at',)
class MeasureItem(models.Model):
item = models.ForeignKey(Item, on_delete=models.CASCADE, blank=True, null=True)
unit = models.ForeignKey(MeasureUnit, on_delete=models.CASCADE, blank=True, null=True)
quantity = models.IntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('created_at',)
My serializer:
from rest_framework import serializers
from .models import Item, MeasureItem
class MeasureUnitSerializer(serializers.ModelSerializer):
class Meta:
model = MeasureItem
fields = ('id', 'unit')
class ItemAdminSerializer(serializers.ModelSerializer):
measure_units = MeasureUnitSerializer(many=True)
class Meta:
model = Item
fields = ('id', 'code', 'current_code', 'title', 'description', 'measure_units')
def create(self, validated_data):
units_data = validated_data.pop('measure_units')
item = Item.objects.create(**validated_data)
for unit_data in units_data:
try:
measure_unit = unit_data['unit']
MeasureItem.objects.create(unit=measure_unit, item=item)
except Exception as e:
print(str(e))
return item
return item
MeasureUnitSerializer is ModelSerializer for MeasureItem model, but you use it for MeasureUnit model in ItemAdminSerializer:
measure_units = MeasureUnitSerializer(many=True)
Since MeasureUnit doesn't have unit field you see error.
You could try to specify source argument of measure_units field:
measure_units = MeasureUnitSerializer(source='measureitem_set', many=True)