teleren/devto huggingface dataset:
Django REST Framework: The powers of a Serializer (1)
Tags: django, original, serializer, rest
Published: 2020-11-29 12:26:46


> Water has been taken for granted. - Jan Eliasson



DRF's Serializer has been proved to be a killing feature. 

Here I am going to share details of updating a Foreign key object data while updating a reverse relation object using serializer.

The point here is that, while we usually use foreign key fields in the serializer for reading operation, we can also use them to write operations.

### Update FK object data:

Let's consider a scenario.

Where we have an account, to which loan applications can be submitted. While approving an application, we need to collect the `approved_amount` and `reason`.


```
class Account(models.Model):
    account_number = models.CharField(max_length=255)
    approved_amount = models.PositiveIntegerField(default=0)
    reason = models.CharField(max_length=255, null=True, blank=True)

    def __str__(self):
        return self.account_number


class LoanApplication(models.Model):

    class Status(models.TextChoices):
        SUBMITTED = 'SUBMITTED', 'Submitted',
        REJECTED = 'REJECTED', 'Rejected'
        APPROVED = 'APPROVED', 'Approved'

    account = models.ForeignKey(Account, on_delete=models.CASCADE)
    status = models.CharField(
        max_length=255, choices=Status.choices, default=Status.SUBMITTED)

    def __str__(self):
        return str(self.account)
``` 


The above requirement shall be done using only one API call.

As shown in the above code shots, we have `approved_amount` and `reason` in the `Account` model, whereas approval shall be done to the `LoanApplication` object. 

Let's see how the serializer tackles the above problem.

As in the below shots, while approval, we collect the amount and reason in the same API. In serializer, just before updating `LoanApplication`, we separate `Account` data and update to the appropriate account, then proceed to update the loan application.


```
class AccountSerializer(serializers.ModelSerializer):

    class Meta:
        model = Account
        fields = '__all__'


class LoanApplicationSerializer(serializers.ModelSerializer):
    approved_amount = serializers.IntegerField(
        source='account.approved_amount')
    reason = serializers.CharField(source='account.reason')

    class Meta:
        model = LoanApplication
        exclude = ('account',)

    def update(self, instance, validated_data):
        account_data = validated_data.pop('account', None)
        if account_data:
            account_serializer = AccountSerializer(
                instance.account, data=account_data, partial=True)
            account_serializer.is_valid(raise_exception=True)
            account_serializer.save()

        return super().update(instance, validated_data)
``` 


### Links:

1.  [Github code](https://github.com/aravindas4/django-shots1/tree/master/app1)
Dashboard UI with Tailwind CSS v2.0 (Dark Mode)
Tags: showdev, tailwindcss, darkmode
Published: 2020-11-29 11:57:27

---
title: Dashboard UI with Tailwind CSS v2.0 (Dark Mode)
published: true
description: An example of using dark mode, which is the new feature of Tailwind CSS
tags: #showdev #tailwind #darkmode
//cover_image: https://direct_url_to_image.jpg
---
Hello everyone. 👋

I've built a dashboard using the Dark Mode feature that comes with the new version of Tailwind CSS. Please note, this feature depends on your [*system color preferences.*](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme)

{% codepen https://codepen.io/knyttneve/pen/NWRWQeB %}
Are you a SOLID developer?
Tags: programming, leadership, productivity, beginners
Published: 2020-11-29 11:42:11

SOLID is an acronym for 5 object-oriented design principles formulated by Robert Martin - [@unclebobmartin](https://twitter.com/unclebobmartin). Following SOLID principles will help you build maintainable and extensible software.

![cv-review](https://learn.coderslang.com/solid-dev-guy.jpeg)

### So, what makes you SOLID?

**S** - Single-responsibility principle
**O** - Open-closed principle
**L** - Liskov substitution principle
**I** - Interface segregation principle
**D** - Dependency inversion principle

### The Single Responsibility Principle (SRP)

> A class should have one and only one reason to change, meaning that a class should have only one job.

You can apply this rule more broadly. Functions, variables, modules. Follow the SRP and don't try to create a Swiss Army knife everywhere you look.

### The Open-closed principle (OCP)

> Objects or entities should be open for extension but closed for modification.

At first, it may seem that there's nothing wrong with modification. Everything changes as they once sang.

The issue with modification is that if you have some function that does multiple things, and you need to modify one of these, you might break other clients. And even if you're so smart and hardworking that you don't mind rewriting them all, others may be.

So, follow the OCP and add extra behavior on top of the existing one, not by modifying the original. If you failed at SRP, it'd be pretty hard to keep up with OCP.

### The Liskov Substitution Principle (LSP)

>  Instances of a superclass should be replaceable with the instances of its subclasses.

In plain English, LSP means that if you have some `Dog` which can `bark()`, it's not very wise to build MechanicalDog that extends Dog and can only `bark()` if provided with batteries and would otherwise throw an Error.

### Interface Segregation Principle (ISP)

> No client should be forced to depend on methods it does not use.

You can consider it an SRP for the interface design.

Declutter and make sure everything is in the right place.

### Dependency inversion principle (DIP)

> Everything should depend on abstractions (interfaces).

The interfaces should never depend on details.

Seems obvious? But look closer and you'll see violations of DIP literally everywhere.

### Conclusion

Apply the SOLID principles today and you'll become a much better developer tomorrow!

P. S. Oh, and don't forget the Agile approach.

> Make it work → Make it clever → Make it fast

Nobody will care about how good your code is if it doesn't solve a problem.

[Learn Full Stack JavaScript](https://js.coderslang.com)
PRE2050
Tags: javascript
Published: 2020-11-29 11:39:42

      Introducing the Website Preloaders of the future PRE2050
------------------------------------------------------------

But First what is preloaders and how it works ? 

Preloading mechanisms work according to a simple principle: an instruction in the source code of a website sets the process in motion and refers to a resource that is to be preloaded. Normally, the applications would determine when to load which content and scripts, and integrate them into the document. In preloading, it is the browser that renders a website and becomes aware of a preload hint. 

Preloading can reduce the loading time of websites and features, thereby improving the user experience. When a user visits a website, certain resources are loaded into the browser's cache using declarative markup. The keyword Preload can be used to preload content that is referenced by the Atrribute link. 

-----------------------------------------------------------

Preloader Tips :

* Is fast to load. You don’t want your preloader to need a preloader.
* Doesn’t run too long or too short. It needs to run just enough for your page to load and no longer.
* Can be branded in your colours or with your logo. It needs to look seamless and not an add-on.
* Suits your brand. Make sure the preloader design is relevant to your business.
* Has a sense of fun or seasonality. You get bonus points for a loading animation with a nice touch of humour, or that matches the season. Yes – you can add Christmas preloaders for a dose of extra Christmas spirit.

---------------------------------------------------------------

                          PRE2050 😍 

Pre2050 - is collecting 6 Creative Loaders is developed to load on screen a waiting spinner plugin for your customers.

You have 6 different spinners to suit your designs.

In just 2 minutes you can configure this codes, with a few steps you will have transitions from page to page on your website.
You also have the option of launching the loader if you are performing an action, to send data by Ajax, wait while a process is running, etc.

A simple, lightweight but very useful scripts, developed in CSS3 compatible with mobile devices and taking advantage of hardware acceleration.
When we are in a higher than screen web, wherever you’re Css Loader always placed in the center of the screen.


Developed By 💜 ShotaZhvania.Dev

DOWNLOAD LINK : https://www.ko-fi.com/s/87dfa05d20
Iterables & Iterators in JS, Part I - Basics (YouTube tutorial)
Published: 2020-11-29 11:30:51

Hi guys!

So far I've been posting regular [articles](https://mpodlasin.com/articles/) on dev.to. This time I've decided to try something different and I've finally started a tech [YouTube channel](https://www.youtube.com/channel/UCF0RK6CA9wpxVrcFbKNG2sA), which will focus on JavaScript, React, and functional programming.

Were are kicking things off with a miniseries about iterables & iterators in JS. Hope you'll enjoy it!

{% youtube keBYj0Un--k %}
Creating my portfolio site
Tags: portfolio, graphql, gatsby, contentfullcms
Published: 2020-11-29 11:19:47

```
Hello dev.to World!
```

This first post will be for me to familiarize with dev.to features and as a first update of creating [my portfolio site - https://wizlee.dev](https://wizlee.dev).

As of this writing, my portfolio site is using a template from https://html5up.net/. As my day work is not web development, I was using the opportunity to learn the basic vanilla html, css & JS. 

Next up, my plan is to use Ema Suriano's [great looking Gatsby starter](https://github.com/EmaSuriano/gatsby-starter-mate) to learn about graphql and to create a striking portfolio site. First task is to personalize and replace the medium posts graphql query to use dev.to instead 😉

Signing off by sharing my newly updated Github profile page below kick-started using Rahul Jain's [github-profile-readme-generator](https://github.com/rahuldkjain/github-profile-readme-generator).

{% github wizlee/wizlee %}
Hey, are you still getting error in mongoDB compass?
Tags: mongodb, compass, installationerror
Published: 2020-11-29 11:03:19

Hey people, I found many of you getting error in installing mongoDB compass. Even I get also. And may be internet has no solution to solve this error. But I read error, read codebase, follow dependencies, done some experiments and finally I find the solution. I posted it on stack overflow.
Link is given here.

{% stackoverflow 64897505 %}
Explain apollo graphql partialRefetch like I'm five
Tags: discuss, explainlikeimfive
Published: 2020-11-29 10:40:05

[Apollo GraphQL Query](https://www.apollographql.com/docs/react/data/queries/) hook has an option called `partialRefetch` and the docs state:

> If true, perform a query refetch if the query result is marked as being partial, and the returned data is reset to an empty Object by the Apollo Client QueryManager (due to a cache miss). The default value is false for backwards-compatibility's sake, but should be changed to true for most use-cases.

Sadly I don't fully get it by reading the docs and searching online.

- What is different for queries using this parameter?
- When to use it?

Please go ahead and ELI5!
Layered architecture
Tags: programming, architecture
Published: 2020-11-29 10:36:51

Layered architecture is the first architectural pattern that we are going to explore. If you haven’t read my article about [software architecture](https://ddimitrov.dev/2020/11/08/what-is-software-architecture/), I suggest you do it before continuing with this one.

## What is a layered architecture?
Simply put, the layered architecture pattern’s main idea is to group and isolate system concerns while defining strict communication direction between them.

Each group of related modules/classes we call layer. Different layers are encapsulated and depend on each other through abstraction and well-defined interfaces.

Layers in this architecture pattern are stacked. The request direction is from the upper layers to the lower layers. In the best-case scenario, a layer can request a layer that is only directly below it.

In sporadic cases, an upper layer is allowed to request a layer two-level or more levels below, but in general, it is considered bad practice.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/olelew72scs1n7tcnkhq.png)

Layered architecture is widespread. We can find it the simple client->server pattern or OSI network model. Also, many enterprise applications implement that pattern.

*In the following examples, we do not discuss cross-cutting concerns and their implementation.*

## What is the difference between layered architecture and N-tier architecture?
There is none significant one. By tier, we consider a physical layer (like SQL server, for example). N describes the number of layers/tiers you have.

In general, both names refer to the principles we discuss in this article.

## Enterprise application example

Most of the layered architecture implementations consist of four layers (ok, three layers, and a tier).

They are:

* Presentation layer
* Business layer
* Data Access layer
* Data Storage tire

Their names are explanatory enough, but let’s discuss them in detail.

## Presentation layer
In the presentation layer, you can find user interface components.

In a standard ASP.NET Core application, these are the Views. The presentation layer, of course, is not limited to any technology. You can have anything that a user can interact with. CLI, SPA, etc.

The presentation layer should not contain business logic and should not access database data directly.

Its only task is to visualize data and dispatch the user’s input. That’s why the presentation layer requests data and sends commands from/to the business layer.
You can read the full article on my programming blog -> [Layered architecture](https://ddimitrov.dev/2020/11/22/layered-architecture-what-is-layered-architecture-and-when-to-use-it/)
Tips For Freshers
Tags: success, freshers, hindi, english
Published: 2020-11-29 10:03:11

#Tips 

1. **Always try to keep improving yourself**
     * Learn New tech things, compete with yourself, aalas mat khao, you should learn to push yourself everyday.
     * Everyday wake up and set your mind to work on your skills, try even if you are not able to concentrate..so that after sometime or somedays your interest will be created automatically.
     * yaad rakho, sunna sab ka hai magar karna wahi hai jo tumhe thik lagta ho.
     * Waqt barbaad mat karo warna ek din waqt tumhe barbaad kardega.
     * Apne career pe hamesha concentrate karo, **Dost**, **Ladki/Ladka**, **Gaadi** wagera sab khud-ba-khud tumhare pas aajayegi ek din.
     * In Simple Terms **INVEST IN YOUR SELF**

2. **Always Explore early: Do mistakes**
     * When yo start exploring things early in your life, you can figure out where your passion lies.
     * Committing mistakes is good but repeating the same in not.
     * **Remember:** Jitni Galti Karoge sikhne waqt utni he aage badhoge, aane walle samay mai.

3. **MONEY or PASSION**
     * Always Follow your passion rather than money, because money is not a big deal, what matters is you **vision** about your future.
     * Your vision for yourself should be the main agenda.
     * Skills, knowledge pe hamesha dhyan dena, paise apne aap aajayega.

4.  **Opportunities**
      * Always look to grab the opportunities, It is good to follow your dream but never ignore the opportunities that come in between.
      * **"If somebody offers you an amazing opportunity but you are not sure you can do it, say yes – then learn how to do it later!"** **-Richard Branson**

5.   **Stick to professionalism**
       * The IT sector is that kind of an industry which requires you to be a professional to the core.
       * If the task given by them are not able to solve then talk to them about it and tell them the issue you are facing in the task.
       * Communicate 

6.   **Expectations** 
       * Remember one thing don't believe and Faith anyone who is saying that I'll help you out to get a job or I have a good source, you just shared me your resume. 
       * They all are useless, it's better to take your own responsibility. 

7.   **College ke us paar tum duniya ko nachate the aur college ke is paar duniya tumhe nachayegi** isliye zaruri hai ki jitna jaldi sudhar jaoge utna he behetar rahega aane walle dino mai.
     * So welcome to this new cycle and remember one thing - “The more value you give to this world the more the world will pay you.”
_So start adding more values in yourself!!_

8.   **It’s good to have intelligence but if you don’t know how to use your emotional quotient you’ll lose the race. Offices are made up of people, who make policies, systems and rules.**
9.   **Last but not the least**
    _Work Smartly_, _Grab opportunities_, _Make a Career Plan_, _Learn_

10.  **Remember:** **Time Ek Chiz Lati Hai Aur Woh Hai Experience, Aur Experience Ka Bohot Value Hai!!**

**--------------:v: Thank You For Reading :smile:--------------**
What is your 3rd party dependencies update strategy in big projects?
Tags: watercooler, discuss
Published: 2020-11-29 09:49:32

I am trying to get some input from people working on large projects with many devs involved, about how do you manage your 3rd party dependencies.
Let me be more specific:
Let’s say that in our organization we are working on several big projects, some are infrastructure projects that are consumed and used by other projects.
Naturally, all projects have 3rd party dependencies and you need to update them at some point.
What is your strategy?
The considerations are (if you have other, please do tell):

security - you don’t want to stay with old versions
same but simply to get the latest bug fixes and updates
you might break often if you keep updating every build for example
when you update your infra projects, you might break your depending projects that are using you as a dependency.
What is your strategy?

* You do something automatic like dependabot? 
* Do you update each time you build and handle breakage as it occur?
* Do you have a “scheduled event” for updating libraries? if so, how often?
* You only update when something demands it (security alert, required feature, another library requires it, etc…)
Something else?
Thanks!
Console.log Development vs Production
Tags: react, javascript, enviroment
Published: 2020-11-29 09:27:33

I was working on a project with some local software house developer and what i notice is they use to much console's in application and these console are all in from local/development  to production which is really bad for the application , so i decided to work on it and make a solution to this, we can create a custom function which will work for use to console data on some specific environment like on local/development but not on production,

i just create a util folder and in it i create a file name utils.js in which i define a function 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/zlmbqs5jyavqmyv7z7jf.png)

in this example you can see i just create a function with name "consoleLog" which console the data with string which comes from parameter pass to this function, ignore the env and if condition , now this console will work on every environment and  console dat,
but we want to console data only in development 

npm i react-dotenv install this library and create .env file on your root folder, and then see the previous logic.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/a3vnsem5wpnakc2td9lv.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/4b6kgcy13sdq835wyzcu.PNG)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/mwkmtu6ane8xfxvyoxlb.PNG)

you can also just do a simple logic in root/app file in componentDidMount/userEfect with 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/hwc00uvtp3jdicjdbovk.png)
Dev-Ops Life Cycle
Tags: devops, docker, webdev
Published: 2020-11-29 09:14:26

**DevOps** is the software enginnering culture that unites the development and operation team up under a umbrella of tools to develop applications and to automate every stage of automation.

The DevOps life cycle consist of 8 phases:
**1.Planning :**
This is the phase where the managers and software developers discuss and plan the aims and objective of application.

**2.Code Phase:**
In this phase programmers than develops a code and make use of tools like _Git_ to store them as different repositories for proper version controll.

**3.Build Phase:**
In this phase tools like _Maven_ and _Gradel_ takes the piece of codes form different repositories and combine them to make a one single application.

**4.Testing Phase:**
This phase consist of continous testing that can be manual and automated to ensure the good code quality.Tools like _Cucumber_ and _Selenium_ are used for purpose.

**5.Integration Phase:**
In this phase,when the testing is complete new features are automatically integrated into the existing code base._Jenkins_ are used to do this.

**6.Deployment Phase:**
In this phase the application is packaged and released from the development servers to the production server.Tools like _XebiaLabs_ and _bmc_ are used to do that .

**7.Operation Phase:**
In this phase the software is deployed and one team intergrate them with the required services and servers._Ansible_,_Chef_ is used for this purpose.

**8.Monitoring Phase:**
After proper deployment the application is then monitored for different aspects and to see different issues and understand  the impact of end users.
How do you deploy your Gatsby website?
Tags: discuss, gatsby, javascript, webdev
Published: 2020-11-29 09:11:23

I'm planning to build a Gatsby based website. I'm new to web dev and its related jargon so I'm still doing research on how this will all come together.

I have a WordPress site I host with Hostinger and need to upgrade my plan to a VPS to be able to host a React-based site. But before I make a decision I wanted to know how others deploy Gatsby sites.

Has anyone used providers that are typically known for hosting CMS based sites for deploying their Gatsby site? Like Hostinger, Namecheap, Bluehost, HostGater, etc..

Or how do you deploy your Gatsby site?

Thanks.