Git Product home page Git Product logo

full-stack-django-and-react's Introduction

Full Stack Django and React

Full Stack Django and React

This is the code repository for Full Stack Django and React, published by Packt.

Get hands-on experience in full-stack web development with Python, React, and AWS

What is this book about?

Django developers often need to rely on front-end developers to build client-side solution for their web apps. By combining the capabilities of React with Django, this book creates a complete learning path to go from being a backend developer to a full stack developer in no time. This book will help you use React to build state-of-the-art UI layouts and Django to create an immaculate backend.

This book covers the following exciting features:

  • Explore how things work differently under the hood in the frontend as well as backend
  • Discover how to build an API with Django
  • Start from scratch to build an intuitive user interface using React capabilities
  • Dockerize and prepare projects for deployment
  • Deploy API and UI on various platforms like AWS and Vercel

If you feel this book is for you, get your copy

Instructions and Navigations

All of the code is organized into folders. For example, Chapter03.

The code will look like the following:

from rest_framework import viewsets
from rest_framework import filters
class AbstractViewSet(viewsets.ModelViewSet):
  filter_backends = [filters.OrderingFilter]
  ordering_fields = ['updated', 'created']
  ordering = ['-updated']

Following is what you need for this book: This book is for Django web developers who want to get started with full-stack development and learn a frontend framework that can be quickly bootstrapped with the backend to build full-stack applications. Familiarity to React and JavaScript would be an added advantage.

With the following software and hardware list you can run all code files present in the book (Chapter 1-16).

Software and Hardware List

Chapter Software/Hardware required OS required
1-16 Python Windows, Mac OS X, and Linux
1-16 JavaScript Windows, Mac OS X, and Linux
1-16 PostgreSQL Windows, Mac OS X, and Linux
1-16 Django Windows, Mac OS X, and Linux
1-16 React Windows, Mac OS X, and Linux
1-16 Docker Windows, Mac OS X, and Linux

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. Click here to download it.

Issue - Initial User Migration Failed with Admin.0001 Dependency

After creating the UserManager and User models, if the migration fails with the following error:
Migration admin.0001_initial is applied before its dependency core_user.0001_initial on database 'default'.

Please try running these commands:
$ sudo su postgres
$ psql
postgres=# DROP DATABASE coredb;
postgres=# CREATE DATABASE coredb;
postgres=# ALTER ROLE core SET client_encoding TO 'utf8';
postgres=# ALTER ROLE core SET default_transaction_isolation TO 'read committed';
postgres=# ALTER ROLE core SET timezone TO 'UTC';
postgres=# ALTER DATABASE coredb OWNER TO core;
postgres=# GRANT ALL PRIVILEGES ON DATABASE coredb TO core;

If you already ran the "makemigrations" for core_user, simply run python manage.py migrate

For more details check out this thread by our reader remyluslosius.

Errata

  • Page 81 (line 19):
post = serializers.SlugRelatedField(queryset=Post.objects.all(), slug_field='public_id')

  def to_representation(self, instance):
        rep = super().to_representation(instance)
        

should be

post = serializers.SlugRelatedField(queryset=Post.objects.all(), slug_field='public_id')

        def validate_author(self, value):
          if self.context["request"].user != value:
            raise ValidationError("You can't create a post for another user.")
        return value
        
        def to_representation(self, instance):
          rep = super().to_representation(instance)

Related products

Get to Know the Author

Kolawole Mangabo is a Software Engineer, currently specializing in HTML, CSS, JavaScript, and Python while regularly using React, Vue, and Django to build single-page applications and marketing landing pages in his daily routine. His goal in a team is to always build products that provide pixel-perfect, performant experiences adjusting business and user needs. When he is not coding, he spends most of his time writing and publishing articles on various websites on topics like software architecture, testing, full-stack development, and developer experience.

Download a free PDF

If you have already purchased a print or Kindle version of this book, you can get a DRM-free PDF version at no cost.
Simply click on the link to claim your free PDF.

https://packt.link/free-ebook/9781803242972

full-stack-django-and-react's People

Contributors

josepha-packt avatar koladev32 avatar markdsouzapackt avatar packt-itservice avatar rajat-packt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

full-stack-django-and-react's Issues

Good to know

in this part `DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': coredb, <---error
'USER': 'core',
'PASSWORD': 'wCh29&HE&T83',
'HOST': 'localhost',
'PORT': '5342',
}
}

` from the book the name coredb is set as a variable. It causes confusion and many errors.

Chapter 2: Auth using JWT's 'UserManager' object has no attribute 'get_object_by_public_id'

I'm currently on Chapter 2 of your book where i'm building out the Auth and getting the user.

I've got to the point where i am trying to use the API to call the users and individual user:
When i hit http://127.0.0.1:8000/api/user i successfully return all users

{
    "count": 1,
    "next": null,
    "previous": null,
    "results": [
        {
            "id": "07c123cefa79459f9f68b6d2455b8f77",
            "username": "john-doe",
            "first_name": "John",
            "last_name": "Doe",
            "email": "[email protected]",
            "is_active": true,
            "created": "2023-10-17T11:17:47.242594Z",
            "updated": "2023-10-17T11:17:47.242600Z"
        }
    ]
}

When i hit http://127.0.0.1:8000/api/user/07c123cefa79459f9f68b6d2455b8f77 it throws this error:

AttributeError: 'UserManager' object has no attribute 'get_object_by_public_id'

I can't find anything online on how to fix this, any ideas what's going wrong?
My User model, serializers and viewsets look like this:
User Model

from django.db import models
import uuid
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin, UserManager
from django.http import Http404
from django.core.exceptions import ObjectDoesNotExist

# Create your models here.


class User(AbstractBaseUser, PermissionsMixin):
    public_id = models.UUIDField(
        db_index=True, unique=True, default=uuid.uuid4, editable=False)
    username = models.CharField(db_index=True, max_length=255, unique=True)
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    email = models.EmailField(db_index=True, unique=True)
    is_active = models.BooleanField(default=True)
    is_superuser = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)
    last_login = models.DateTimeField(auto_now_add=True)
    created = models.DateTimeField(auto_now=True)
    updated = models.DateTimeField(auto_now_add=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']
    objects = UserManager()

    def __str__(self):
        return f"{self.email}"

    @property
    def name(self):
        return f"{self.first_name} {self.last_name}"


class UserManager(BaseUserManager):
    def get_object_by_public_id(self, public_id):
        try:
            instance = self.get(public_id=public_id)
            return instance
        except (ObjectDoesNotExist, ValueError, TypeError):

            return Http404

    def create_user(self, username, email, password=None, **kwargs):
        """
        Create and return a `User` with an email, phone_number, username, password.
        """
        if username is None:
            raise TypeError('Users must have a username')
        if email is None:
            raise TypeError('Users must have ab email')
        if password is None:
            raise TypeError('Users must have a password')

        user = self.model(username=username,
                          email=self.normalize_email(email), **kwargs)
        user.save(using=self._db)
        return user

    def create_super_user(self, username, email, password, **kwargs):
        """
        Create and return a `User` with superuser (admin) permissions.
        """
        if password is None:
            raise TypeError('Superuser must have a password')
        if email is None:
            raise TypeError('Superuser must have an email')
        if username is None:
            raise TypeError('Superuser must have a username')

        user = self.create_user(username, email, password, **kwargs)
        user.is_superuser = True
        user.is_staff = True
        user.save(using=self._db)
        return user

User Viewsets

from rest_framework.permissions import AllowAny, BasePermission
from rest_framework import viewsets
from core.user.serializers import UserSerializer
from core.user.models import User


class UserViewSet(viewsets.ModelViewSet):
    http_method_names = ('patch', 'get')
    # using AllowAny + BasePermission to allow bypassing of permissions correctly
    permission_classes = (AllowAny, BasePermission)
    serializer_class = UserSerializer

    def get_queryset(self):
        if self.request.user.is_superuser:
            return User.objects.all()
        return User.objects.exclude(is_superuser=True)

    def get_object(self):
        obj = User.objects.get_object_by_public_id(self.kwargs['pk'])
        self.check_object_permissions(self.request, obj)
        return obj

User Serializers

from rest_framework import serializers
from core.user.models import User


class UserSerializer(serializers.ModelSerializer):
    id = serializers.UUIDField(
        source='public_id', read_only=True, format='hex')
    created = serializers.DateTimeField(read_only=True)
    updated = serializers.DateTimeField(read_only=True)

    class Meta:
        model = User
        fields = [
            'id',
            'username',
            'first_name',
            'last_name',
            'email',
            'is_active',
            'created',
            'updated'
        ]
        read_only_field = ['is_active']

Full error output:

Internal Server Error: /api/user/07c123cefa79459f9f68b6d2455b8f77/
Traceback (most recent call last):
  File "/Users/gareth/Development/django-social/social/venv/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "/Users/gareth/Development/django-social/social/venv/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/gareth/Development/django-social/social/venv/lib/python3.11/site-packages/django/views/decorators/csrf.py", line 56, in wrapper_view
    return view_func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/gareth/Development/django-social/social/venv/lib/python3.11/site-packages/rest_framework/viewsets.py", line 125, in view
    return self.dispatch(request, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/gareth/Development/django-social/social/venv/lib/python3.11/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/gareth/Development/django-social/social/venv/lib/python3.11/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/Users/gareth/Development/django-social/social/venv/lib/python3.11/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/Users/gareth/Development/django-social/social/venv/lib/python3.11/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/gareth/Development/django-social/social/venv/lib/python3.11/site-packages/rest_framework/mixins.py", line 54, in retrieve
    instance = self.get_object()
               ^^^^^^^^^^^^^^^^^
  File "/Users/gareth/Development/django-social/social/core/user/viewsets.py", line 21, in get_object
    obj = User.objects.get_object_by_public_id(self.kwargs['pk'])
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'UserManager' object has no attribute 'get_object_by_public_id'

Packages Versions:
Django==4.2.6
psycopg2_binary==2.9.9
djangorestframework==3.14.0
django-filter==23.3
djangorestframework-simplejwt==5.3.0

Password not getting hashed in the database

¿Has anyone experienced this issue?

Here's my code for "create_user()" in user/models.py, following the book but also after searching for solutions in the internet:

def create_user(self, username, email, password=None, **kwargs):
    """Create and return a `User` with an email,
    phone number, username and password."""
    if username is None:
        raise TypeError('Users must have a username.')
    if email is None:
        raise TypeError('Users must have an email.')
    if password is None:
        raise TypeError('User must have a password.')
    email = self.normalize_email(email)
    user = self.model(username=username, email=email, **kwargs)
    user.set_password(password)
    user.save(using=self._db)

    return user

The password is stored in plain text, so when I try to login a user it doesn't check ok the credentials.

Any help will be appreciated. Thanks.

Error on Creating a post

when put the right credentials to post request ,it getting an error !

{
"detail": "Authentication credentials were not provided."
}

I cross check each codelines ,there is no in error on viewsets.py file of post app

Error after add router

Hello,
First of all, thank you for your amazing work. I've just started to read the book and have enjoyed it so far.

I'm at chapter 2, section Adding a router. After adding to the router like this, in file routers.py:
router.register(r'user', UserViewSet, basename='user') urlpatterns = [ *router.urls, ]
Then I ran the server
python manage.py runserver

After that, made a GET request
http://127.0.0.1:8000/api/user/
then the following error occurred:

Using the URLconf defined in CoreRoot.urls, Django tried these URL patterns, in this order:
admin/
The current path, api/user/, didn’t match any of these.

So I tried to figure the cause, and modified the urls.py file like this (the book does not mention to modify this file)
urlpatterns = [ path("admin/", admin.site.urls), path("api/", include(("core.routers"))), ]

And I tried to request again, another error happened:

TypeError at /api/user/
'str' object is not callable

I've wondered has someone else encountered this issue like I did?

Not an issue, just a question / suggestion

As I was reading Chapter 5: Testing the REST API, I thought of adding testing for like and remove_like, so I would like to check this code and tell me if it is ok or if something else should be added/removed/changed.

This is added in core/post/tests/test_viewsets.py

def test_like(self, client, user, post):
    client.force_authenticate(user=user)
    response = client.post(self.endpoint + str(post.public_id) + "/like/")
    assert response.status_code == status.HTTP_200_OK
    assert response.data['id'] == post.public_id.hex
    assert response.data['likes_count'] == 1

def test_remove_like(self, client, user, post):
    client.force_authenticate(user=user)
    response = client.post(
        self.endpoint + str(post.public_id) + "/remove_like/")
    assert response.status_code == status.HTTP_200_OK
    assert response.data['id'] == post.public_id.hex
    assert response.data['likes_count'] == 0

def test_like_anonymous(self, client, user, post):
    response = client.post(self.endpoint + str(post.public_id) + "/like/")
    assert response.status_code == status.HTTP_401_UNAUTHORIZED

def test_remove_like_anonymous(self, client, user, post):
    response = client.post(
        self.endpoint + str(post.public_id) + "/remove_like/")
    assert response.status_code == status.HTTP_401_UNAUTHORIZED

Any opinion and review will be appreciated.

I keep getting the same error after making the post request.

Great! Let’s test the new endpoint with Insomnia. In the collection of requests for this project, create a
new POST request. The URL will be as follows: localhost:8000/api/auth/register/.
As a body for the request, you can pass the following:
{
"username": "mouse21",
"first_name": "Mickey",
"last_name": "Mouse",
"password": "12345678",
"email": "[email protected]"
}
Also, you didnt mentioned anything about the type of header in Insomnia.

While setting up postgres here are some of my challenges

The book is an excellent resource for both beginners and experienced programmers. The book covers a wide range of topics, from basic syntax and programming concepts to more advanced techniques like web development and data analysis.

The authors provide clear explanations and practical examples for each topic, making it easy to follow along and apply the concepts in your own projects. The book is well-organized and easy to navigate, with helpful summaries and exercises at the end of each chapter.

One minor issue I encountered was that some of the code examples/steps did not work as expected, which caused some frustration and confusion. I don't know whether this is the right place to express my frustration and my workaround for people who might be facing similar issues.

My setup is
PC Description: Ubuntu 22.04.2 LTS
Postgres: PostgreSQL 15.2 (Ubuntu 15.2-1.pgdg22.04+1) on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0, 64-bit
Django = 4.0

psycopg2.OperationalError: connection to server at "localhost" (127.0.0.1), port 5342 failed: Connection refused
        Is the server running on that host and accepting TCP/IP connections?

Then I followed a tutorial on DigitalOcean
which showed some further tweaks to the

ALTER ROLE core SET client_encoding TO 'utf8';
ALTER ROLE core SET default_transaction_isolation TO 'read committed';
ALTER ROLE core SET timezone TO 'UTC';

Then I got this error

psycopg2.errors.InsufficientPrivilege: permission denied for schema public
LINE 1: CREATE TABLE "django_migrations" ("id" bigserial NOT NULL PR....

Then I solved this using this page on stackoverflow using this:

GRANT postgres TO core;

Initial User Migration Failed with Admin.0001 Dependency [Solved]

After creating the UserManager and User models, the migration failed with the error below.

Migration admin.0001_initial is applied before its dependency core_user.0001_initial on database 'default'.

I followed this discussion thread's advice to delete/drop the database.

$ sudo su postgres
$ psql

postgres=# DROP DATABASE coredb;

Now, recreate the database. Remember the user 'core' still exists. There's no need to try to create it.

postgres=# CREATE DATABASE coredb;
postgres=# ALTER ROLE core SET client_encoding TO 'utf8';
postgres=# ALTER ROLE core SET default_transaction_isolation TO 'read committed';
postgres=# ALTER ROLE core SET timezone TO 'UTC';
postgres=# ALTER DATABASE coredb OWNER TO core;
postgres=# GRANT ALL PRIVILEGES ON DATABASE coredb TO core;

If you already ran the "makemigrations" for core_user, simply run python manage.py migrate

It works for me!

insomnia test failed

I followed the book instructions step by step and when I got to insomnia test , I got a 404 not found error message telling me that : the current path, api/, didn't match any of these

In one part of the code, is_staff is not defined and it would be a nightmare for the people reading this book.

In core/user/model.py

`class User(AbstractBaseUser, PermissionsMixin):

public_id = models.UUIDField(
    db_index=True, unique=True, default=uuid.uuid4, editable=False)
username = models.CharField(db_index=True, max_length=255, unique=True)
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
email = models.EmailField(db_index=True, unique=True)
is_active = models.BooleanField(default=True)
is_superuser = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)  <----- you will have to add this!!!!
created = models.DateTimeField(auto_now=True)
updated = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
objects = UserManager()`

I am trying to document things so people dont give up

RegistrationForm.js

Following the book and it shows a src/components/RegistrationForm.js . I don't see that in this structure. Can you help me?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.