Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add view permissions in Django 1.9
I am using Django 1.9, and I need to add a permission for a user to only be able to view data in the admin panel. Currently my only options are add, change & delete. Does anyone know how I can go about doing this? I don't really know what to try. -
Create Custom Mixins in Django
I want to create mixins from normal function. from taggit.models import Tag def remove_all_tags_without_objects(): for tag in Tag.objects.all(): if tag.taggit_taggeditem_items.count() == 0: tag.delete() else: pass I want to convert above function into mixin os i can re use it. -
python-django on gcp server not responding
I have deployed the python-Django project on GCP instance. The problem I am facing is that it responds on external IP for a couple of hours then it failed to respond.when I try to open VM-instance it failed to open my ssh instance.in order to start every time I need to stop and start the instance again.Thanks in advance -
Django cron error No module named 'my_app'
I'm trying to send some emails in Django by Django Cronjob but getting an error ModuleNotFoundError: No module named 'my_app' Cron Job Code class MyCronJob(CronJobBase): RUN_EVERY_MINS = 5 schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'app.MyCronJob' def do(self): email = EmailMessage('hi', 'message', to=['demo@gmail.com']) email.send() I've tried from .. import my_app but getting an error after adding this import line as well ValueError: attempted relative import beyond top-level package -
How to compare integer field with Datetime in django?
Here I have a simple function for sending leave request and accepting by the admin.This code works for now but I want to add some feature here.For example if the user enter day = 2 which is IntegerField then it get stores into databse then after the leave has been accepted by the function below def accept_leave(request,pk): I want to display the remaining days of leave(Example:1 day 12 hours and 30 sec. remaining to complete leave ).After 2 days completed it should display some message like you leave has been completed. I got no idea for starting this .How can I do it ?Any help would be great. Is there any mistake in my approach ? models.py class Leave(models.Model): staff = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,related_name='staff_leave') organization = models.ForeignKey(Organization,on_delete=models.CASCADE,related_name='staff_leave') sub = models.CharField(max_length=300) msg = models.TextField() day = models.IntegerField(default=0) is_accepted = models.BooleanField(default=False) is_rejected = models.BooleanField(default=False) sent_on = models.DateTimeField(auto_now_add=True) views.py def send_leave_request(request): form = MakeLeaveForm() if request.method == 'POST': form = MakeLeaveForm(request.POST) if form.is_valid(): leave_days = form.cleaned_data['day'] org = form.cleaned_data['organization'] leave = form.save(commit=False) leave.staff = request.user leave.organization = org leave.save() return redirect('organization:view_leaves') return render(request,'organization/send_leaves.html',{'form':form}) def accept_leave(request,pk): leave = get_object_or_404(Leave, pk=pk) leave.is_accepted = True leave.is_rejected = False leave.day = ? leave.save() return redirect('organization:leave_detail',leave.pk) -
Django Rest Framework: Retrieving associated items from foreign key relationship in serializer
I'm trying to retrieve associated (FK) rows/values through my serializer. I have an Order model and a Food model, where one or many Food belongs to one Order like so: class Order(models.Model): total_price = models.DecimalField(decimal_places=2, max_digits=4, null=False) status = models.ForeignKey(OrderStatus, related_name='order', on_delete=models.CASCADE, null=False) placed_datetime = models.DateTimeField(null=False) class Food(models.Model): order = models.ForeignKey(Order, related_name='food', on_delete=models.CASCADE) quantity = models.IntegerField(null=False) price = models.DecimalField(decimal_places=2, max_digits=4, null=False) And my serializers: # Order Details serializer class OrderDetailsSerializer(serializers.ModelSerializer): foods = FoodSerializer(many=True, read_only=True) class Meta: model = Order fields = ("id", "status", "total_price", "placed_datetime", "foods") status = serializers.SerializerMethodField("get_status_label") def get_status_label(self, obj): return obj.status.label class FoodSerializer(serializers.ModelSerializer): ingredients = FoodIngredientSerializer(many=True, read_only=True) class Meta: model = Food fields = ("size", "quantity", "price", "ingredients") No luck with the above approach. -
Django-filter displaying all the records, While submitting empty form
Right now i have completed filtering function using django-filters. But while submitting the form empty, its fetching all the records. My code is working fine. I have restricted django-filter from displaying all the records while page startup .Also i don't want to display all the records while submitting empty form. version_filter.html <form action="" method="GET"> <button class="btn btn-primary btn-sm" type="submit">Submit</button> {{filters.form.as_table}} </form> views.py def bfs_version_filter(request): version_obj = bfs_versions.objects.all() filter_obj = version_filter(request.GET, queryset = version_obj) return render(request, 'bfslite/version_filter.html', { 'filters' : filter_obj,}) filter.py class version_filter(django_filters.FilterSet): bfs_version_code = django_filters.CharFilter(lookup_expr = 'icontains', label = "Version") bfs_version_status = django_filters.ChoiceFilter(field_name = "bfs_version_status", choices=TASK_STATUS, lookup_expr='exact', label = "Version Status") bfs_version_end_date = django_filters.DateFilter(widget=forms.widgets.DateInput(attrs={'type':'date'}), label= "End Date") bfs_version_uploaded_on = django_filters.DateRangeFilter(label= "Uploaded on") bfs_task_code__bfs_client_eta = django_filters.DateFilter(widget=forms.widgets.DateInput(attrs={'type':'date'}), label= "Client Date") bfs_shot_code__bfs_shot_code = django_filters.CharFilter(lookup_expr = 'exact', label = "Shot") bfs_task_code__bfs_task_name = django_filters.CharFilter(lookup_expr = 'exact', label = "Task") #payable and paid bfs_version_payable = django_filters.BooleanFilter(field_name='bfs_version_payable', lookup_expr= 'exact', label = "Payable") bfs_version_paid = django_filters.BooleanFilter(field_name='bfs_version_paid', lookup_expr= 'exact', label = "Paid") def __init__(self, *args, **kwargs): super(version_filter, self).__init__(*args, **kwargs) if self.data == {}: self.queryset = self.queryset.none() class Meta: model=bfs_versions fields=[ 'bfs_version_code', 'bfs_version_status', 'bfs_version_end_date', 'bfs_version_uploaded_on', 'bfs_task_code__bfs_client_eta', 'bfs_shot_code__bfs_shot_code', 'bfs_task_code__bfs_task_name', 'bfs_version_payable', 'bfs_version_paid', ] -
How to authenticate user if password set as set_unusable_password()
I want to realize login for user with password which I set in models with help of set_unusable_password. I don't know how to realize authenticate for this user. Can I decode password which is record in db or can I realize my own authenticate function and after that use login(request, user)? Method for creating user with unusable password: @staticmethod def create_user_via_facebook(first_name, last_name, userId): user = User(first_name=first_name, last_name=last_name, email=userId) user.set_unusable_password() user.save() return user -
Django prefixes dbo. while saving models to SQL server
After migrating my models to SQL Server, all of the tables showed up under the schema dbo (default schema). I have set my default schema from within SQL Server to the schema of my choice. After re-migration, all the tables were created in the dbo schema again. Using: db_table = 'defaultschema\".\"table' resulted in django just creating the model as dbo.defaultschema.table Is there any solution or workaround to this specific issue? -
I am trying to update data in database using get() method, but get() doesn't update in django
am trying to update using get() in django but not updated in databse while it gives message as it updated well am trying to update using get() in django but not updated in databse while it gives message as it updated well, I tried to use filter() and it working well, but the problem is filter does not work professional in updating data, check my code below. please I want to use get() to make sure my things is updated well thank you. enter code here @require_http_methods(["PATCH", "PUT"]) def update_product(request, id=None): items_from_user = json.loads(request.body.decode('utf8')) try: Product.objects.values().get(id=id).update(**items_from_user) return JsonResponse({ 'message': 'Product {} updated'.format(id) }) except Product.DoesNotExist as error: return JsonResponse({ 'message': str(error) }, status=404) except Exception as error: return JsonResponse({ 'message': str(error) }, status=422) -
Fallback to normal function if celery is not active
What I require is a simple hack for running function synchronously if celery is not active. What I tried is: is_celery_working returns False although celery and Redis both are running (ran celery -A project worker -l debug and redis-server respectively). Also get_celery_worker_status is always giving error in status. I am using celery with Django. from project.celery import app def is_celery_working(): result = app.control.broadcast('ping', reply=True, limit=1) return bool(result) # True if at least one result def sync_async(func): if is_celery_working(): return func.delay else: return func sync_async(some_func)(**its_args, **its_kwrgs) def get_celery_worker_status(): error_key = 'error' try: from celery.task.control import inspect insp = inspect() d = insp.stats() if not d: d = {error_key: 'No running Celery workers were found.'} except IOError as e: from errno import errorcode msg = "Error connecting to the backend: " + str(e) if len(e.args) > 0 and errorcode.get(e.args[0]) == 'ECONNREFUSED': msg += ' Check that the RabbitMQ server is running.' d = {error_key: msg} except ImportError as e: d = {error_key: str(e)} return d def sync_async(func): status = get_celery_worker_status() if 'error' not in status: return func.delay else: return func sync_async(some_func)(**its_args, **its_kwrgs) -
I am sending POST request, but got error which says that get method is not allowed
I am sending POST request, but got this error: "detail": "Method \"GET\" not allowed." enter image description here enter image description here -
how to open a postgres database created with docker in a database client?
I have a question about how to open a database created with docker using https://github.com/cookiecutter/cookiecutter in a database client imagen1 imagen2 imagen3 -
django-autocomplete-light Remove Media (JS, CSS)
How can I remove all the media (JS & CSS files), which is added by django-autocomplete-light, from the form? I tried to override self.media in the form with None or even a list. I also tried to create a Media Class inside my Form, but this did not help either. The only thing that worked so far, was to remove the media directly from the source code of the library, but this isn't a appropriate solution. I know that the JS & CSS is needed. But my templates already provide all the necessary files. Form class LogEntryFilterForm(forms.Form): user = ModelChoiceField( queryset=PimUser.objects.all(), widget=autocomplete.ModelSelect2( url='accounts_autocomplete', attrs={ 'theme': 'bootstrap4', 'data-minimum-input-length': 2, } ) ) def __init__(self, *args, **kwargs): request = CrequestMiddleware.get_request() self.helper = FormHelper() self.helper.form_method = 'get' self.helper.form_action = '.' self.helper.form_class = 'form-filter-vertical form-bordered' self.helper.layout = self.__get_layout() super().__init__(*args, **kwargs) self.fields['ip'].widget.attrs['placeholder'] = request.META.get('REMOTE_ADDR') Media Output <link href="/static/vendor/select2/dist/css/select2.css" type="text/css" media="screen" rel="stylesheet"> <link href="/static/admin/css/autocomplete.css" type="text/css" media="screen" rel="stylesheet"> <link href="/static/autocomplete_light/select2.css" type="text/css" media="screen" rel="stylesheet"> <script type="text/javascript" src="/static/admin/js/vendor/jquery/jquery.js"></script> <script type="text/javascript" src="/static/autocomplete_light/jquery.init.js"></script> <script type="text/javascript" src="/static/vendor/select2/dist/js/select2.full.js"></script> <script type="text/javascript" src="/static/vendor/select2/dist/js/i18n/de.js"></script> <script type="text/javascript" src="/static/autocomplete_light/autocomplete.init.js"></script> <script type="text/javascript" src="/static/autocomplete_light/forward.js"></script> <script type="text/javascript" src="/static/autocomplete_light/select2.js"></script> <script type="text/javascript" src="/static/autocomplete_light/jquery.post-setup.js"></script> -
Django rest url routers on class based views
I would like to get the details of my submodules on a route with multiple parameters. My existing routes right now are: http://localhost:8000/api/module/ - Gets all modules http://localhost:8000/api/module/1/ - Gets all modules and connected submodules I would like to do http://localhost:8000/api/module/1/submodules/1 which will get the details of the submodules. How should i do this using class based views? Below is my existing code: Views.py class CourseModuleViewSet(viewsets.ModelViewSet): queryset = CourseModule.objects.all() serializer_class = CourseModuleSerializer def retrieve(self, request, pk=None): coursemodule = CourseModule.objects.get(id=pk) submodule = SubModule.objects.filter(submodule_module_id=pk) serializer = SubModuleSerializer(submodule, many=True) response = {'message': 'Sucess!', 'result': serializer.data} return Response(serializer.data, status=status.HTTP_200_OK) Serializers.py class CourseModuleSerializer(serializers.ModelSerializer): class Meta: model = CourseModule fields = ['class_id', 'coursemodule_title', 'coursemodule_date_created', 'coursemodule_last_modified', 'coursemodule_created_by'] class SubModuleSerializer(serializers.ModelSerializer): submodule_module_id = CourseModuleSerializer(many=False) class Meta: model = SubModule fields = ['submodule_module_id','submodule_title', 'submodule_date_created', 'submodule_last_modified', 'submodule_created_by'] urls.py router = routers.DefaultRouter() router.register('module', CourseModuleViewSet) urlpatterns = [ path('', include(router.urls)), ] -
How can I make my tags go to a new line whenever they go outside the div django-taggit
So for starters I am using django-taggit for a tagging system on my site. Everything was going well until I decided to try really long strings and many of them. It turns out it spills out of the div. I would like to know how can I make it go to a new line in the div whenever this happens, or even to limit the max characters allowed for each tag/limit the amount of tags allowed. Here is the relevant models.py class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=75) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) image = models.ImageField(upload_to='post_images',blank=True,null=True) file = models.FileField(upload_to='post_files',blank=True,null=True) published_date = models.DateTimeField(blank=True,null=True,auto_now_add=True) comments_disabled = models.BooleanField(default=False) NSFW = models.BooleanField(default=False) spoiler = models.BooleanField(default=False) tags = TaggableManager() And here is the relevant HTML file {% for tag in post.tags.all %} <li class="tag-list-box"><a class="tag-list-style" href="{% url 'mainapp:tagged' tag.slug %}">{{ tag.name }}</a></li>&nbsp;&nbsp; {% empty %} <li>No tags</li> {% endfor %} So how would I go about breaking a line when the tags start spilling out of the div or even how to limit the actual number of allowed tags -
Nginx (proxy_pass) + Gunicorn can’t be reached
I want to run django with gunicorn and nginx as a proxy server on Ubuntu. The site works with djangos dev server: python manage.py runserver 0.0.0.0:8000 The site works with gunicorns server (even static files don't work): gunicorn my_project.wsgi --bind 0.0.0.0:8000 But with nginx on top I get the following error: This site can’t be reached ... refused to connect. ERR_CONNECTION_REFUSED Also both nginx log files error.log & access.log are empty. Here is how I configured nginx: server { listen 80; server_name my_ip_address; location / { proxy_pass http://127.0.0.1:8001; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Scheme $scheme; } } In this case gunicorn runs with --bind 127.0.0.1:8001 of course. Status check (service nginx status) returns: ● nginx.service - A high performance web server and a reverse proxy server Active: active (running) since Fri 2019-09-20 07:41:00 UTC; 1min 19s ago Starting A high performance web server and a reverse proxy server... nginx.service: Failed to parse PID from file /run/nginx.pid: Invalid argument Started A high performance web server and a reverse proxy server. -
Post filter on the basis of tags in django taggit(package)
I just installed django taggit by following official documentation. Every things work fine but when i click on the tags it doesn't filter post containing that tags here is my code. Code containing models.py file .............. from taggit.managers import TaggableManager .................. class Post(models.Model): STATUS_CHOICES = ((DRAFT, _('draft')), (PUBLISHED, _('published'))) author = models.ForeignKey(get_user_model(), verbose_name=_( "Author"), on_delete=models.CASCADE, related_name='blog_posts') title = models.CharField(_("Title"), max_length=200, unique=True) slug = models.SlugField(_("Slug"), unique_for_date='publish') status = models.IntegerField( _('status'), db_index=True, choices=STATUS_CHOICES, default=DRAFT) tags = TaggableManager() def __str__(self): return self.title def get_absolute_url(self): return reverse("blog:post_detail", kwargs={ "pk": self.pk }) code contain views.py file from django.views.generic import ListView class PostListView(ListView): model = Post queryset = Post.published.all().order_by('-publish') context_object_name = 'post_list' template_name = "client/pages/blog_list.html" paginate_by = 7 urls.py file from .views import PostListView, .......... path('tag/<slug:tag_slug>/', PostListView.as_view(), name='post_list_by_tag'), .......... and in the templates file <ul class="tags-inline"> <li>Tags:</li> {% for tag in post_detail.tags.all %} <li> <a href="{% url 'blog:post_list_by_tag' tag.slug %}">{{ tag.name }}</a> , </li> {% endfor %} </ul> -
Django: Translation only works for some strings
I'm trying to translate my django project from English into German. It currently consists of two apps. The mainapp is translated correctly. The other app is fully translated in the django.po file but only a few translated strings will be shown and the other ones still remain in English. For compilation of my language files (one for each of the currently two apps) I always execute the following commands in the root directory of my project: django-admin makemessages -l de # Now doing some translations django-admin compilemessages When I change any translation string and execute makemessage and compilemessage, django will still use the old translation and not the new one. So it looks like it worked some time ago but not something is going wrong with compiling/using the translations. In this template for example the "Log in" and the "Sign up" string are translated correctly, but the "Need an account?" string is not because it was added when the translations didn't work anymore. But unfortunately I have no idea what changed and why it's not working anymore. {% extends "mainapp/base.html" %} {% load crispy_forms_tags %} {% load i18n %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} … -
I'm trying to update nested serializer it's giving me an error paper_description with this id already exists?
Django Rest Framework inserting and updating writable nested serializer I trying to insert and update a writable nested serializer with Django Rest Framework, following examples like this. But it doesn't work. What could I having doing wrong? Controller class JobCardViewSet(ModelViewSet): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) serializer_class = JobCardSerializer http_method_names = ('get', 'post', 'put', 'patch') def get_queryset(self): if 'key' in self.request.GET: key = self.request.GET['key'] return JobCard.objects.filter(models.Q(job_order_no__icontains=key) | models.Q(job_name__icontains=key)) if 'party' in self.request.GET: return JobCard.objects.filter(party_name__name__icontains=self.request.GET['party']) else: return JobCard.objects.all() def create(self, request, *args, **kwargs): self.serializer_class = JobCardPostSerializer return super(JobCardViewSet, self).create(request, *args, **kwargs) def update(self, request, *args, **kwargs): self.serializer_class = JobCardPostSerializer return super(JobCardViewSet, self).update(request, *args, **kwargs) Serializer My serializer class PaperDescriptionPostSerializer(ModelSerializer): class Meta: model = PaperDescription fields = '__all__' class JobCardPostSerializer(ModelSerializer): paper_description = PaperDescriptionPostSerializer(many=True) class Meta: model = JobCard fields = '__all__' def create(self, validated_data): paper_description_list = validated_data.pop('paper_description') job_card = JobCard.objects.create(**validated_data) for paper in paper_description_list: paper.update({"party_name": job_card.party_name}) paper.update({"job_order_no": job_card.job_order_no}) paper.update({"job_name": job_card.job_name}) paper.update({"job_date": job_card.job_date}) paper.update({"job_type": job_card.job_type}) job_card.paper_description.add(PaperDescription.objects.create(**paper)) return job_card def update(self, instance, validated_data): paper_description = validated_data.pop('paper_description') instance.job_name = validated_data.get("job_name", instance.job_name) instance.job_date = validated_data.get("job_date", instance.job_date) instance.delivery_date = validated_data.get("delivery_date", instance.delivery_date) instance.job_created_by = validated_data.get("job_created_by", instance.job_created_by) instance.die_no = validated_data.get("die_no", instance.die_no) instance.job_re_print = validated_data.get("job_re_print", instance.job_re_print) instance.remarks = validated_data.get("remarks", instance.remarks) instance.update_reason = validated_data.get("update_reason", instance.update_reason) instance.job_details = validated_data.get("job_details", instance.job_details) instance.party_name = … -
How to post an image with other data in the json file using angularjs form
I'm trying to create multiple form under tabs with previous tab data been used in the next tab and each form has a save button which saves the data for the next tab using angularjs. Everything is working fine with code. All of the form data is added to single field in the model which is a JSONField. Except I have a form which has a file field usually images I am stuck with the upload of these images to the json field. var app = angular.module('app', []); app.controller('enviromentController', function ($scope, $http) { $scope.saveEnvironment = function () { $http({ method: 'PUT', "url": "{% url 'core:api:edit-environement' env_id=env_id %}", "data": angular.copy($scope.env), "headers": { "accept": "application/json", "content-type": "application/json", "Authorization": "Token " + localStorage.getItem('token') } }).then(function () { inform("Saved", "Published data"); }); this is my form <div class="tab-content" id="myTabContent" style="min-height:375px"> <div class="tab-pane active" id="environment" role="tabpanel" aria-labelledby="environment-tab"> <div class="form-group col-lg-5"> <label class="form-control-label">Title </label> <input type="text" class="form-control" ng-model="env.title" required /> </div> <div class="form-group col-lg-5"> <label class="form-control-label">Department</label> <select class="form-control" ng-model="env.department" ng-options="c.id as c.name for c in departments" required> </select> </div> <div class="form-group col-lg-5"> <label class="form-control-label" for="appname">App Name</label> <select class="form-control" ng-model="env.app_name" ng-options="c.id as c.name for c in app_name" required> </select> </div> </div> <div class="tab-pane" id="room" role="tabpanel" aria-labelledby="room-tab"> <div … -
DRF serializer field renamed to it's source in validated data
I have a drf serializer with a field I would like to rename: class UserBulkUploadSerializer(serializers.Serializer): ... is_admin = serializers.BooleanField(required=False, source='administrator') However, in validated_data attribute it's got renamed back to the source attribute value. I'm doing this: serializer = UserBulkUploadSerializer(data=data) serializer.is_valid() return serializer.validated_data And there's no is_admin key in there, it's administrator. Is there a way to overcome this and make it is_admin in validated_data? -
How do i make many to many field as a chekbox items in template.?
I have 3 models one is Category(Fields = category_name) and another one is SubSategory(Fields = category(ForeignKey to Category),sub_category).and another model is DummyModel. # Model class DummyModel(models.Model): name = models.CharField(max_length=20) email = models.EmailField() category = models.ManyToManyField(Category) sub_category = models.ManyToManyField(SubCategory) This is my view #view class StartProjectView(View): template_name = 'start-project.html' def get(self, request): form = StartProjectForm() return render(request, self.template_name, {'form': form}) def post(self, request): form = StartProjectForm(request.POST) if form.is_valid(): form.save() form = StartProjectForm() return render(request, self.template_name, {'form':form}) return HttpResponse("<h2>Done</h2>") This is my Template # Template <form method="post"> {% csrf_token %} <p>name: <input type="text" name="name"></p> <p>Email: <input type="text" name="email"></p> {% for form in form %} <input type="checkbox" name="category">{{ form.category }} {% endfor %} <br> {% for form in form %} <input type="checkbox" name="sub_category">{{ form.sub_category }} {% endfor %} <button type="submit">Start Now</button> </form> I want category and subcategory in my template as checkbox items. How do I do that.? -
Browser shows variable refered before assign
I am new to python and hardly tried to figure out the problem of usese of variable from another if statement in the same function here is my code: def post(self, request, **kwargs): selected_membership_type = request.POST.get('membership_type') user_membership = get_user_membership(request) user_subscription = get_user_subscription(request) selected_membership_qs = Membership.objects.filter( membership_type=selected_membership_type) if selected_membership_qs.exists(): selected_membership = selected_membership_qs.first() ''' ========== VALIDATION ========== ''' # selected_membership = selected_membership_qs.first() if user_membership.membership == selected_membership: if user_subscription == None: messages.info(request,"You already have this membership.Your \ next payment is due {}".format('get this value from stripe')) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) -
Fetching Child Category Objects django python
I am trying to get child listing with category . serializers.py: class ChildSerializer(serializers.HyperlinkedModelSerializer): category_id = serializers.PrimaryKeyRelatedField(queryset = Category.objects.all(), source = 'category.id') class Meta: model = SubCategory fields = ('url','id', 'sub_category_name', 'category_id') def create(self, validate_data): #subject = SubCategory.objects.create subject = SubCategory.objects.create(Category=validated_data['category']['id'], sub_category_name=validated_data['sub_category_name']) return SubCategory class CategorySerializers(serializers.ModelSerializer): children = ChildSerializer(many=True, read_only=True) class Meta: model = Category fields = ('id','name','slug','children') views.py: class CategoryView(viewsets.ModelViewSet): queryset = Category.objects.all() serializer_class = serializers.CategorySerializers this is the api output: { "id": 30, "name": "akera", "slug": "akera", "children": [] }, { "id": 31, "name": "sda", "slug": "sd", "children": [] }, { "id": 6, "name": "Technology", "slug": "12", "children": [ 29, 30, 31 ] }, { "id": 7, "name": "Festival", "slug": "12", "children": [] }, currently its getting only category id of subcategory i want to fetch the subcategory name and id with category...................................................