teleren/devto huggingface dataset:
DRF create validation in serializer
Published: 2023-11-07 10:43:33

I will show two different validations, one with the validation of one attribute of the serializer and the second with the validation of different attributes.

## validation of different attributes in `validate()`:

```python
# serializers.py

class ProjectCreateSerializer(serializers.ModelSerializer):

    class Meta:
        model = Project
        fields = [
            "id",
            "name",
            "description",
            "project_type",
        ]

    def validate(self, attrs):
        if (
            self.context["view"]
            .project.filter(name=attrs["name"], project_type=attrs["project_type"])
            .exists()
        ):
            raise serializers.ValidationError("Attention! This project exists already.")
        return attrs
```

`self.context["view"].project` this project property/attribute is created in view (ProjectViewSet). With this syntax we can get the project property and filter for existing projects. If this combination of `name` and `project_type` is found, the ValidationError will be raised. Otherwise the project will be validated.


## validation with one attributes in `validate_user()`:

`validate_user` the `user` part is the name of the attribute from the serializer. If you have an attribute `project` the function name would be `validate_project()`.

```python
# serializers.py

class ContributorSerializer(serializers.ModelSerializer):

    # create attribute 'user', which is write_only because we just need to give a value
    user = serializers.IntegerField(write_only=True)

    class Meta:
        model = UserModel
        fields = ["id", "user"]

    def validate_user(self, value):
        user = UserModel.objects.filter(pk=value).first()

        if user is None:
            raise serializers.ValidationError("User does not exists!")

        if user.is_superuser:
            raise serializers.ValidationError(
                "Superusers cannot be added as contributors."
            )

        if self.context["view"].project.contributors.filter(pk=value).exists():
            raise serializers.ValidationError(
                "This user is already a contributor of this project."
            )

        return user
```
What problems can happen with different serializer in DRF?
Published: 2023-11-07 12:52:27

I have created a Mixin for the serializer classes. I wanted to create several serializer for different tasks. So, I need for special actions special serializers.


```python
# mixins.py

class SerializerClassMixin:
    serializer_create_class = None
    serializer_details_class = None

    def get_serializer_class(self):
        if self.action == "create":
            return self.serializer_create_class
        elif self.action == "retrieve":
            return self.serializer_details_class
        return super().get_serializer_class()
```
 
For the actions create and retrieve (get details), I have created new class attributes to call the serializer. The `return super().get_serializer_class()` tells the Mixin to use the `get_serializer_class()` for any other actions. 


These are all possible actions:
- list (GET)
- retrieve (GET)
- create (POST)
- update (PUT)
- partial_update (PATCH)
- destroy (DELETE)


For my project, I have decided to create two serializers: CreateSerializer and DetailSerializer.

```python
# views.py

class IssueViewSet(SerializerClassMixin, viewsets.ModelViewSet):

    serializer_class = IssueDetailSerializer
    serializer_create_class = IssueCreateSerializer
    serializer_detail_class = IssueDetailSerializer
```

For these project I have created two different serializers: IssueCreateSerializer and IssueDetailSerializer. 

Why have I used the IssueDetailSerializer for all other actions? If I use the IssueCreateSerializer for update action (PUT or PATCH) of the attributes like `description` or `assigned_to`, the result in Postman is a ValidationError because the IssueCreateSerializer checks if the `name`, `tag`, `state` and `priority` in one issue already exists. And if you do not change the `name`, `tag`, `state` and `priority` the update is failing. 
In IssueDetailSerializer I do not do any validation.


To visualize the serializers:

```python
# serializers.py

class IssueCreateSerializer(serializers.ModelSerializer):
    """create and lists Issues
    validate if the issue already exists"""

    class Meta:
        model = Issue
        fields = [
            "id",
            "assigned_to",
            "name",
            "description",
            "tag",
            "state",
            "priority",
        ]

    def validate(self, attrs):
        if (
            self.context["view"]
            .issue.filter(
                name=attrs["name"],
                tag=attrs["tag"],
                state=attrs["state"],
                priority=attrs["priority"],
            )
            .exists()
        ):
            raise serializers.ValidationError("Attention! This issue exists already.")

        return attrs


class IssueDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = Issue
        fields = [
            "id",
            "author",
            "assigned_to",
            "name",
            "description",
            "tag",
            "state",
            "priority",
            "project",
            "created_time",
        ]
```
Uzak GNS3 Sunucusuna Bağlanma
Tags: linux, beginners, tutorial, opensource
Published: 2023-11-07 12:51:03

GNS3 Ağ yapılarımızı simüle edebildiğimiz açık kaynak kodlu, ücretsiz ve güçlü bir program. Büyük projeler üzerinde çalışılacağız zaman kaynak gereksinimleri de bir hayli yüksek olabilmekte. Bundan dolayı remote server seçeneği bizleri kurtarıyor. 

Bu yazımızda Uzak (Remote) GNS sunucusuna nasıl bağlanabileceğimizi göreceğiz.


Bilgisysarımızda GNS3 kurulu değilse [buradan](https://www.gns3.com/software/download) gerçekleştirebilirsiniz.

Kurulum sonrası açılan GNS arayüzünüzde **Edit -> Preferences** seçeneklerine tıklıyoruz.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5fqil2qpl3xzzlblyf2l.png)

Açılan ekranda Main Server ve Remote Server adlarında iki seçenek çıkmakta. Ana sunucunuzu uzak sunucu yapmak için **Enable local server** işaretini kapatıyoruz.

Remote main server alanına ise uzak sunucumuzun bilgilerini yazıyoruz.

Akabinde Apply ve Ok butonlarına basarak ayarlarımızı kaydediyoruz.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2i4n3ppmyuasbgc9v78o.png)

İşlem sonrasında Servers summary alanına sunucumuz yeşil olarak geldiyse başarılı bir şekilde bağlandığımızı düşünebiliriz.

Ana sunucunuz dururken yeni sunucular eklemek isterseniz **Preferences** alanından girdiğimiz **Server** sayfasında **Remote Servers** altını seçebiliriz.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/npoewnyhqlj78pwdvmh0.png)



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xl38zp3bjvh4coojbuxx.png)

Add butonuna basarak ekleme işlemini gerçekleştirebilirsiniz.
  
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d3vq5u8333mzvndbndm3.png)


**_Not: Eğer versiyon hatası veriyorsa istemcinizi sunucunuz ile aynı versiyon olacak şekilde yükleyebilirsiniz veya suncunuzu ve istemcinizi son sürüme yükseltebilirsiniz_**
One App, All Devices: Unlock the Efficiency of Cross-Platform Development
Published: 2023-11-07 12:45:18

Experience the wonder of Dallas with our [cross-platform app](https://www.technbrains.com/). Our specialists make sure it functions seamlessly on iOS and Android, offering you a quality, informative journey without extra costs.

**Social Links**

Facebook

https://www.facebook.com/pages/category/Software-Company/Technbrains-100478948441594/

Twitter

https://twitter.com/technbrains

Instagram

https://www.instagram.com/technbrains/

LinkedIn

https://www.linkedin.com/company/technbrains
Placeholder Contributor
Tags: hack23contributor
Published: 2023-11-07 12:44:23

<!-- ✨This template is only meant to get your ideas going, so please feel free to write your own title, structure, and words! ✨ -->

### Intro
<!-- Share a bit about yourself as a contributor. Is this your first Hacktoberfest, or have you contributed to others? Feel free to embed your GitHub account by using {% embed LINK %} -->

### Highs and Lows
<!-- What were some of your biggest accomplishments or light-bulb moments this month? Did any problems come up that seemed impossible to fix? How did you adapt in those cases?  -->

### Growth
<!-- What was your skillset before Hacktoberfest 2023 and how did it improve? Have your learning or career goals changed since working on these new projects? -->
Introduction: Get Ready for Interview Prep Series!
Published: 2023-11-07 12:35:31

Hey there, folks! 😃 I'm absolutely thrilled to kick off a brand new series of articles here on [dev.to](https://dev.to). In this series, I'll be covering everything you need for interview preparation in both frontend and backend technologies. 🚀

## What to Expect

I've got a comprehensive list of questions, and we're going to dive deep into both theory and practice. 💡

### Theory-Based Questions

In the initial section of this series, we'll focus on the essential theory-based questions. We'll cover a wide array of topics in the technologies I've mentioned below. 📚

### Exciting Coding Challenges

Once we've laid the foundation with theory and concepts, we'll venture into the fun part—coding questions! Expect to see the most commonly asked coding questions related to React, JavaScript, data structures, algorithms (DSA), and more. 💻

So, gear up for an exciting journey through the world of interview preparation. We're going to equip you with the knowledge and skills you need to ace those technical interviews. Stay tuned for more! 🚀

### List of topics that we will be covering throughout the series

**Languages**
- HTML
- CSS
- JavaScript
- TypeScript
- Node JS
- SQL

**Frameworks**
- React
- Nest JS
- Express JS

**Libraries**
- Ant Design
- Material-UI
- Redux Toolkit

**Databases**
- MongoDB
- Postgres SQL

**Other Tools**
- GIT
- NPM

**Data Structures & Algorithms**
**System Design**
**Short articles/topics**

Thank you for your support. If you have any queries, please write in the comments. Do like and share the article; it is highly appreciated. And if you have any suggestions, also include. 🙏👍😊
Adding API Key Middleware in NestJS
Tags: nestjs, api, apikey, middleware
Published: 2023-11-07 12:25:09

API Key Middleware is a secure way to protect your API by requiring users to include a valid API key in every request. In this guide, we'll walk through the steps to add API Key middleware to your NestJS application.

## Step 1: Install NestJS

Before you begin, make sure you have Node.js and NestJS installed on your computer. If not, you can install NestJS with the following command:

```bash
npm install -g @nestjs/cli
nest new my-api
cd my-api
```

## Step 2: Configure Environment

Set up environment variables to store your API key. You can use [nestjs/config](https://github.com/nestjs/config) to manage configuration. Create a `.env` file in your project directory and add the API key:

```dotenv
API_KEY=your-api-key
```

Next, ensure you have set up the `ConfigModule` correctly in your AppModule:

```jsx
import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";

@Module({
  imports: [ConfigModule.forRoot()],
})
export class AppModule {}
```

## Step 3: Create Middleware

Create an API Key middleware named `ApiKeyMiddleware`. Create a file named `api-key.middleware.ts` in the appropriate directory in your project and add the following code:
[more...](https://blog.awahids.my.id/blog/adding-api-key-middleware-in-nestjs)
Wiselok Techsolution: Innovative Digital Marketing Strategies in Jaipur
Tags: seo, digital, marketing, ecommerce
Published: 2023-11-07 12:18:11

In the vibrant city of Jaipur, amidst the rich cultural heritage and modern dynamism, a digital marketing company is making waves by revolutionizing the way businesses connect with their audiences. Wiseloktechsolution, a dynamic and [Digital Marketing Company In Jaipu](https://wiseloktechsolution.com/)r innovative digital marketing agency, has been a game-changer for businesses in Jaipur and beyond. With a focus on creativity, data-driven strategies, and a passion for client success, this company is at the forefront of transforming the digital landscape.

The Power of Digital Marketing:
In an age where the digital world is an integral part of our daily lives, businesses need to adapt to this changing landscape. Wiseloktechsolution understands the power of digital marketing, and their mission is to help the best Digital Marketing Company In Jaipur businesses leverage this power to grow and succeed.

From small startups to established enterprises, digital marketing has the potential to level the playing field. It provides the opportunity to reach a vast and diverse audience, generate leads, and increase sales. However, the digital marketing landscape is complex and constantly evolving. This is where Wiseloktechsolution comes into play.

Innovative Solutions:
Wiseloktechsolution is not your typical run-of-the-mill digital marketing agency. They take a unique and innovative approach to help businesses stand out in the digital world. Their team of experts understands that one [Digital Marketing service in Jaipur ](https://wiseloktechsolution.com/)size does not fit all, and they tailor their strategies to suit the specific needs and goals of each client.

Whether it's search engine optimization (SEO), social media marketing, pay-per-click (PPC) advertising, content marketing, or email marketing, Wiseloktechsolution has the expertise to create a custom solution that delivers results. They also specialize in website development and design, ensuring that your online presence is not only attractive but also optimized for conversions.

Data-Driven Decision Making:
One of the cornerstones of Wiseloktechsolution's success is their commitment to data-driven decision making. They understand that the digital landscape is driven by data, and by analyzing this [SEO Company In Jaipur data](https://wiseloktechsolution.com/), they can refine and optimize their strategies to achieve the best possible results.

Their team works closely with clients, providing regular updates, reports, and insights to ensure that everyone is on the same page. They believe in open and transparent communication, which fosters a sense of trust and collaboration.


Client-Centric Approach:

Through a combination of analytics, keyword research, and performance tracking, they provide businesses with a clear and comprehensive view of their digital marketing efforts. This transparency allows clients to [E Commerce Services In Jaipur](https://wiseloktechsolution.com/) make informed decisions and understand the impact of their investments.
AI is nice you said? Look what happened at my OpenFest talk. 🤖
Tags: ai, opensource, openai, eventsinyourcity
Published: 2023-11-07 12:08:12

Hey community. I read a lot of good words about the AI and how helpful it is for your work.

I was presenting at OpenFest 2023 in Bulgaria and my AI assistant went nuts.

{% vimeo 882042227%}

Be careful!
24. Continuing with my first assignment (Day 22)
Published: 2023-11-07 11:43:01

Today, and once again I spent a bit of time building my portfolio/profile website for my assignment. I do find code interesting, and I look forward to tinkering with my html and CSS, every day, even if it's for an hour or so.

In the evening, I had a 1:1 virtual class with my tutor to help me understand why the responsiveness of my page broke (especially the navigation bar) when I used Partial files. In reality, it wasn't those files but just that I didn't wrap my `<div class=nav-items" </div>` within another <div> tag, and then use that one to center it, a margin around.

We went through a bit of Media Queries as well. I inquired as to the best screen sizes we should be using while setting up Media Queries, and he referred me to [this page on Bulma](https://bulma.io/documentation/overview/responsiveness/) where you can find the 5 main screen sizes to use:

```
mobile: up to 768px

tablet: from 769px

desktop: from 1024px

widescreen: from 1216px

fullhd: from 1408px
```

So, that's what I will do. But, I think just the mobile, tablet, and desktop will do.

Overall, I have mostly finished the full website:

- Homepage: DONE
- About: DONE
- Skills, Portfolio, Experience: DONE
- Blog home page: PENDING
- 5 Blog articles: PENDING
- Contact: PENDING

Besides the above, I have to create the following as well:

- Figma wireframe for all the pages (3 versions - mobile, tablet & desktop!)
- a PowerPoint presentation
- a video presentation

Plenty remaining!

How do you eat an elephant?

Bite by bite.
Revolutionize Your MySQL Development with Brand New dbForge Studio for MySQL 10.0
Published: 2023-11-07 11:42:37

Devart has rolled out one of the most expansive sets of new features and enhancements for dbForge Studio for MySQL, an all-in-one IDE for MySQL development, management, and administration. The biggest feature in the set is the integrated source control.

Devart, one of the leading developers of database management software, ALM solutions, and data providers for the most popular database servers, has released a grand update for dbForge Studio MySQL (v10.0) and dbForge Edge (v2.0). 

The killer feature of the enhanced dbForge Studio for MySQL is the newly integrated source control, which simplifies and streamlines team-driven database development, supporting all popular version control systems. It allows users to do the following:

- Version-control database schemas and static table data
- Manage database versioning under the dedicated or shared development model
- Commit and revert changes in databases with dependency awareness
- Pull remote changes to a local database copy
- Review and resolve conflicts
- Run quick comparisons of database versions
- View the history of changes

The following feature groups of the Studio have also been considerably enhanced:

- Context-aware code completion and syntax check
- Database design
- Database comparison and synchronization
- Find Invalid Objects
- Security Manager
- Connectivity and general features

To learn more about the recent release, please visit https://blog.devart.com/meet-the-grand-new-dbforge-studio-mysql-10-0-with-integrated-source-control.html 

About Devart

Devart is a multi-product company, one of the leading developers of database management software, ALM solutions, data providers for database servers, as well as data integration and backup solutions.

For additional information about Devart, please visit https://www.devart.com/.
Apache Log4j Exposed: Unraveling a Different Security Threat
Tags: threatanalysis
Published: 2023-11-07 11:24:29

Get the latest insights on the newest Apache Log4j vulnerabilities, and learn how this same wolf keeps adopting different disguises. Equip yourself with the knowledge you need to stay ahead of the curve and safeguard your infrastructure. To learn more, Visit https://portsys.com/apache-log4j-same-wolf-different-vulnerability-2/ now!
Zero Trust Access: The Modern Solution for Ultimate Data Security & Privacy
Tags: zerotrustaccess
Published: 2023-11-07 11:16:57

Attain all-encompassing data protection and bolster your cybersecurity with zero trust access. Start transforming your security infrastructure to meet the demands of a rapidly changing digital landscape at https://www.portsys.com/. Upgrade to a security model that delivers peace of mind and ensures business continuity
Error: __str__ returned non-string (type User)
Published: 2023-11-07 11:09:28

I faced this error: `__str__ returned non-string (type User)` in admin tool when clicking on a project to display the details. This error can also happen in terminal when doing:

```bash
# terminal

>>> Contributor.objects.all().first()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/doro/.local/share/virtualenvs/SoftDesk_project-rOWNEwjK/lib/python3.10/site-packages/django/db/models/base.py", line 588, in __repr__
    return "<%s: %s>" % (self.__class__.__name__, self)
TypeError: __str__ returned non-string (type User)
```


The solution I came up with:

```python
# models.py

class Contributor(models.Model):

    user = models.ForeignKey(
        "api.User",
        on_delete=models.CASCADE,
        related_name="users",
        verbose_name=_("user"),
    )

    def __str__(self):
        return self.user.username


class Project(models.Model):

    name = models.CharField(max_length=100, verbose_name=_("name of project"))
    author = models.ForeignKey(
        "api.Contributor",
        on_delete=models.CASCADE,
        blank=True,
        related_name="project_author",
        verbose_name=_("project author"),
    )

    def __str__(self):
        return f"{self.name} <{self.author.user}>"
```

The error was pointing to the `__str__` method of the Contributor model. When I added `.username` the error was gone. With `self.user` I was just pointing to the user model but not to the attribute which should be displayed. 

It has to be a string like the username, first_name, last_name etc.
Optimism vs Arbitrum: A Comparative Analysis of Leading Ethereum Layer-2 Solutions
Tags: optimismvsarbitrum, ethereum, layer2solutions
Published: 2023-11-07 11:08:00

In the realm of blockchain technology, Ethereum has emerged as a prominent platform for decentralized applications (dApps) and smart contracts. However, the Ethereum network has faced scalability challenges, leading to congestion and high transaction fees. To address these issues, [layer-2 solutions](https://www.codezeros.com/layer-2-blockchain-solutions) have been developed, offering increased throughput and lower fees without compromising on security. Among the leading layer-2 solutions are Optimism and Arbitrum, both of which utilize optimistic rollups, a scaling technique that batches multiple transactions off-chain before finalizing them on the Ethereum mainnet.

## Optimism
Optimism employs a single-round fraud proof mechanism, where the validity of transactions is challenged within a specific time frame. If no challenges are raised, the transactions are considered valid and finalized on the mainnet. This approach offers faster transaction speeds but may incur higher fees due to the computational overhead of fraud proofs on the mainnet.

## Arbitrum
In contrast, Arbitrum utilizes a multi-round fraud proof mechanism, which involves multiple rounds of challenges and responses. This approach, while slightly slower than Optimism, is more efficient in terms of gas costs. Arbitrum also supports a native Arbitrum Virtual Machine (AVM) that expands compatibility beyond Solidity, the primary programming language for Ethereum smart contracts.

Also Read : [Difference between Optimism And Arbitrum](https://www.codezeros.com/optimism-vs-arbitrum-comparing-the-two-popular-ethereum-layer2-rollups)

## Key Comparisons
Here's a comparative overview of key aspects of Optimism and Arbitrum:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4p6x3ngpcjf7mcgtxnjq.png)

## Choosing the Right Layer-2 Solution
The choice between Optimism and Arbitrum depends on specific needs and priorities. Developers seeking faster transaction speeds and compatibility with existing Ethereum applications may prefer Optimism. On the other hand, those prioritizing cost-effectiveness and support for a wider range of programming languages may find Arbitrum more suitable.

## Conclusion
Optimism and Arbitrum represent significant advancements in Ethereum's scalability, offering users and developers a compelling alternative to the congested mainnet. As both solutions continue to evolve, they are poised to play a crucial role in shaping the future of Ethereum and the broader blockchain ecosystem.