In this article I will explain how to create an application with Django-Rest-Framework and Vue.js. I will not describe step by step, but will outline only the main points that you need to know about. You can see the entire project code here.
Django application will include a user app with a custom user model. Create a Django project and app Users:
django-admin startproject gcode_server
cd gcode_server
python manage.py startapp users
The user model will look like this:
# gcode_server/users/models.py
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField('Email', unique=True)
first_name = models.CharField('First Name', max_length=30)
last_name = models.CharField('Last Name', max_length=30)
phone = models.CharField('Phone', max_length=30, blank=True)
is_staff = models.BooleanField('Is Staff', default=False, help_text='If user is staff')
is_active = models.BooleanField('Is Active', default=False, help_text='Is user is active')
date_joined = models.DateTimeField('Date Joined', default=timezone.now)
USERNAME_FIELD = 'email'
objects = CustomUserManager()
class Meta:
verbose_name = 'user'
verbose_name_plural = 'Users'
ordering = ['date_joined']
def __str__(self):
return self.email
USERNAME_FIELD = 'email' ==> we have indicated which field will be used as USERNAME (as login when entering).
Our new user model must be specified in the settings file:
# gcode_server/settings.py
AUTH_USER_MODEL = 'users.CustomUser'
Now we need to prepare the Django app for use with Django-Rest-Framework:
1) We install Django-Rest-Framework, django-cors-headers, django-rest-authtoken.
django-cors-headers will help us make requests from the Vue.js application
django-rest-authtoken help to use the token for authentication
Rest-Framework settings:
# gcode_server/settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
),
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'PAGE_SIZE': 7
}
CORS_ALLOWED_ORIGINS = [
"http://localhost:8080",
]
DEFAULT_AUTHENTICATION_CLASSES ==> specify, how authentication will take
DEFAULT_PERMISSION_CLASSES (AllowAny) ==> requests for all endpoints can be made by anyone
DEFAULT_PAGINATION_CLASS ==> pagination for displaying lists (7 per page)
CORS_ALLOWED_ORIGINS ==> from where we can make cross-site requests
Continued in Part II
Post your comment