Convert Figma logo to code with AI

gothinkster logodjango-realworld-example-app

No description available

1,611
638
1,611
34

Top Related Projects

Exemplary real world application built with React + Redux

ASP.NET Core backend implementation for RealWorld

Example Spring codebase containing real world examples (CRUD, auth, advanced patterns, etc) that adheres to the RealWorld API spec.

Exemplary real world backend API built with Laravel

Quick Overview

The gothinkster/django-realworld-example-app is a Django implementation of the "RealWorld" application. It serves as a demonstration of how to build a full-stack application using Django, following best practices and modern development standards. This project is part of the larger "RealWorld" initiative, which aims to create exemplary fullstack Medium.com clones using various frontend and backend technologies.

Pros

  • Provides a comprehensive example of a real-world Django application
  • Follows best practices and modern Django development standards
  • Includes authentication, user profiles, article creation and management
  • Well-structured codebase with clear separation of concerns

Cons

  • May not cover all advanced Django features or edge cases
  • Documentation could be more extensive for beginners
  • Limited frontend implementation (focuses primarily on backend)
  • May require updates to keep up with the latest Django versions

Code Examples

  1. User Model Definition:
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _

class User(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(db_index=True, max_length=255, unique=True)
    email = models.EmailField(db_index=True, unique=True)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    objects = UserManager()

    def __str__(self):
        return self.email
  1. Article Serializer:
from rest_framework import serializers
from .models import Article, Comment, Tag
from profiles.serializers import ProfileSerializer

class ArticleSerializer(serializers.ModelSerializer):
    author = ProfileSerializer(read_only=True)
    description = serializers.CharField(required=False)
    slug = serializers.SlugField(required=False)
    tagList = TagRelatedField(many=True, required=False, source='tags')
    createdAt = serializers.SerializerMethodField(method_name='get_created_at')
    updatedAt = serializers.SerializerMethodField(method_name='get_updated_at')
    favorited = serializers.SerializerMethodField()
    favoritesCount = serializers.SerializerMethodField(
        method_name='get_favorites_count'
    )

    class Meta:
        model = Article
        fields = (
            'author',
            'body',
            'createdAt',
            'description',
            'favorited',
            'favoritesCount',
            'slug',
            'tagList',
            'title',
            'updatedAt',
        )
  1. Article View:
from rest_framework import generics, mixins, status, viewsets
from rest_framework.exceptions import NotFound
from rest_framework.permissions import (
    AllowAny, IsAuthenticated, IsAuthenticatedOrReadOnly
)
from rest_framework.response import Response
from rest_framework.views import APIView

from .models import Article, Comment, Tag
from .renderers import ArticleJSONRenderer, CommentJSONRenderer
from .serializers import ArticleSerializer, CommentSerializer, TagSerializer

class ArticleViewSet(mixins.CreateModelMixin, 
                     mixins.ListModelMixin,
                     mixins.RetrieveModelMixin,
                     viewsets.GenericViewSet):

    lookup_field = 'slug'
    queryset = Article.objects.select_related('author', 'author__user')
    permission_classes = (IsAuthenticatedOrReadOnly,)
    renderer_classes = (ArticleJSONRenderer,)
    serializer_class = ArticleSerializer

    def create(self, request):
        serializer_context = {
            'author': request.user.profile,
            'request': request

Competitor Comparisons

Pros of node-express-realworld-example-app

  • More lightweight and faster to set up, ideal for small to medium-sized projects
  • Larger ecosystem of npm packages, providing more flexibility in choosing libraries
  • JavaScript-based, allowing for full-stack development with a single language

Cons of node-express-realworld-example-app

  • Less built-in features compared to Django, requiring more manual configuration
  • Potentially less scalable for large, complex applications without additional architecture
  • Lacks Django's robust admin interface and ORM capabilities out of the box

Code Comparison

node-express-realworld-example-app:

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello World!');
});

django-realworld-example-app:

from django.http import HttpResponse
from django.urls import path

def hello_world(request):
    return HttpResponse("Hello World!")

urlpatterns = [
    path('', hello_world),
]

Both examples demonstrate a simple "Hello World" route, showcasing the syntax differences between Express.js and Django. The Express.js version is more concise, while the Django version requires separate URL configuration but offers a more structured approach to routing.

Exemplary real world application built with React + Redux

Pros of react-redux-realworld-example-app

  • Offers a more interactive and responsive user interface due to React's component-based architecture
  • Provides better state management with Redux, making it easier to handle complex application states
  • Allows for easier testing of individual components and actions

Cons of react-redux-realworld-example-app

  • Steeper learning curve for developers new to React and Redux ecosystems
  • Requires more initial setup and configuration compared to the Django-based alternative
  • May have slower initial page load times due to the client-side rendering approach

Code Comparison

react-redux-realworld-example-app:

const mapStateToProps = state => ({
  ...state.article,
  currentUser: state.common.currentUser
});

const mapDispatchToProps = dispatch => ({
  onLoad: payload => dispatch({ type: ARTICLE_PAGE_LOADED, payload }),
  onUnload: () => dispatch({ type: ARTICLE_PAGE_UNLOADED })
});

django-realworld-example-app:

class ArticleViewSet(mixins.CreateModelMixin, 
                     mixins.ListModelMixin,
                     mixins.RetrieveModelMixin,
                     viewsets.GenericViewSet):
    lookup_field = 'slug'
    queryset = Article.objects.select_related('author', 'author__user')
    permission_classes = (IsAuthenticatedOrReadOnly,)
    serializer_class = ArticleSerializer

The React-Redux example showcases client-side state management and component mapping, while the Django example demonstrates server-side view handling and database querying.

ASP.NET Core backend implementation for RealWorld

Pros of aspnetcore-realworld-example-app

  • Built on ASP.NET Core, offering better performance and cross-platform support
  • Utilizes Entity Framework Core for efficient database operations
  • Implements a clean architecture with separation of concerns

Cons of aspnetcore-realworld-example-app

  • Steeper learning curve for developers not familiar with C# and .NET ecosystem
  • Less extensive third-party package ecosystem compared to Django
  • Potentially more verbose code due to C# language characteristics

Code Comparison

django-realworld-example-app:

class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(
        max_length=128,
        min_length=8,
        write_only=True
    )

    class Meta:
        model = User
        fields = ('email', 'username', 'password', 'token',)

aspnetcore-realworld-example-app:

public class UserDto
{
    public string Email { get; set; }
    public string Token { get; set; }
    public string Username { get; set; }
    public string Bio { get; set; }
    public string Image { get; set; }
}

The Django example uses a serializer with built-in validation, while the ASP.NET Core example uses a simple DTO class. The ASP.NET Core approach requires separate validation logic, but offers more flexibility in data transformation.

Example Spring codebase containing real world examples (CRUD, auth, advanced patterns, etc) that adheres to the RealWorld API spec.

Pros of spring-boot-realworld-example-app

  • Utilizes Spring Boot's robust ecosystem and extensive libraries
  • Offers better performance for large-scale applications
  • Provides built-in support for microservices architecture

Cons of spring-boot-realworld-example-app

  • Steeper learning curve for developers new to Java and Spring Boot
  • More verbose code compared to Django's simplicity
  • Requires more configuration and boilerplate code

Code Comparison

spring-boot-realworld-example-app:

@RestController
@RequestMapping("/api/users")
public class UserController {
    @PostMapping("/login")
    public ResponseEntity<?> login(@Valid @RequestBody LoginParam loginParam) {
        // Login logic
    }
}

django-realworld-example-app:

class LoginAPIView(APIView):
    def post(self, request):
        user = request.data.get('user', {})
        serializer = LoginSerializer(data=user)
        serializer.is_valid(raise_exception=True)
        # Login logic

The Spring Boot example uses annotations for routing and request handling, while Django relies on class-based views and serializers. Spring Boot's approach is more explicit but requires more code, whereas Django's implementation is more concise and follows Python's simplicity.

Both repositories implement the RealWorld API spec, providing developers with examples of building real-world applications using different frameworks. The choice between them depends on the developer's familiarity with the language, project requirements, and scalability needs.

Exemplary real world backend API built with Laravel

Pros of laravel-realworld-example-app

  • More active development with recent commits and updates
  • Larger community support and contributions
  • Better documentation and setup instructions

Cons of laravel-realworld-example-app

  • Steeper learning curve for developers new to PHP or Laravel
  • Less flexibility in terms of database choices (primarily focused on MySQL)
  • Potentially higher resource consumption compared to Django

Code Comparison

Laravel (laravel-realworld-example-app):

public function login(Request $request)
{
    $credentials = $request->only('email', 'password');
    if (Auth::attempt($credentials)) {
        return $this->respondWithToken(Auth::user());
    }
    return response()->json(['error' => 'Unauthorized'], 401);
}

Django (django-realworld-example-app):

class LoginAPIView(APIView):
    def post(self, request):
        user = request.data.get('user', {})
        serializer = LoginSerializer(data=user)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        return Response(UserSerializer(user).data)

The Laravel example showcases a more straightforward authentication process, while the Django version uses serializers for data validation and processing. Both approaches have their merits, with Laravel's being more concise and Django's offering more flexibility in data handling.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Django DRF Example App

Example Django DRF codebase containing real world examples (CRUD, auth, advanced patterns, etc) that adheres to the RealWorld API spec.

This repo is functionality complete — PR's and issues welcome!

Installation

  1. Clone this repository: git clone git@github.com:gothinkster/productionready-django-api.git.
  2. cd into conduit-django: cd productionready-django-api.
  3. Install pyenv.
  4. Install pyenv-virtualenv.
  5. Install Python 3.5.2: pyenv install 3.5.2.
  6. Create a new virtualenv called productionready: pyenv virtualenv 3.5.2 productionready.
  7. Set the local virtualenv to productionready: pyenv local productionready.
  8. Reload the pyenv environment: pyenv rehash.

If all went well then your command line prompt should now start with (productionready).

If your command line prompt does not start with (productionready) at this point, try running pyenv activate productionready or cd ../productionready-django-api.

If pyenv is still not working, visit us in the Thinkster Slack channel so we can help you out.