풀스택 개발 공부로그

Django Model Extend

|

django user extend

Extending the existing User model

Customizing authentication in Django | Django documentation | Django

There are two ways to extend the default User model without substituting your own model. If the changes you need are purely behavioral, and don’t require any change to what is stored in the database, you can create a proxy model based on User . This allows for any of the features offered by proxy models including default ordering, custom managers, or custom model methods. If you wish to store information related to User, you can use a OneToOneField to a model containing the fields for additional information. This one-to-one model is often called a profile model, as it might store non-auth related information about a site user. For example you might create an Employee model:

User 모델을 확장하는 방법은 2가지가 있다. 저장 되어있는 데이터베이스를 변경할 필요 없이 함수같은 동작의 변경에만 관심있다면 proxy model이 적합하다. 정렬방법, custom manages, user model methods 등. 두번 째로 User모델과 관련된 추가적인 정보를 저장하고 싶다면 OneToOne필드가 좋다. 보통 profile model이라고 일컬어진다.

from django.contrib.auth.models import User

class Employee(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    department = models.CharField(max_length=100)

Assuming an existing Employee Fred Smith who has both a User and Employee model, you can access the related information using Django’s standard related model conventions:

u = User.objects.get(username='fsmith')
freds_department = u.employee.department

Substituting a custom User model

Customizing authentication in Django | Django documentation | Django

Some kinds of projects may have authentication requirements for which Django’s built-in User model is not always appropriate. For instance, on some sites it makes more sense to use an email address as your identification token instead of a username. Django allows you to override the default user model by providing a value for the AUTH_USER_MODEL setting that references a custom model:

장고 빌트인 User모델이 적합하지 않은 경우들도 많다. user를 식별할 토큰으로 username 대신 email이 필요할수도 있다. 장고에서는 AUTH_USER_MODEL을 통해 override할 수 있다.

settings.py 의 AUTH_USER_MODEL

AUTH_USER_MODEL = 'myapp.MyUser'

Default: ’auth.User’

You cannot change the AUTH_USER_MODEL setting during the lifetime of a project (i.e. once you have made and migrated models that depend on it) without serious effort. It is intended to be set at the project start, and the model it refers to must be available in the first migration of the app that it lives in. See Substituting a custom User model for more details.

Using a custom user model when starting a project

If you’re starting a new project, it’s highly recommended to set up a custom user model, even if the default User model is sufficient for you. This model behaves identically to the default user model, but you’ll be able to customize it in the future if the need arises:

지금 당장은 장고에서 기본으로 제공하는 USER모델로 충분하다 하더라도 아래와 같이 코드를 작성하는것이 좋다. 추후에 커스텀하기 편하다.

from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
    pass

Referencing theUsermodel

If you reference User directly (for example, by referring to it in a foreign key), your code will not work in projects where the AUTH_USER_MODEL setting has been changed to a different user model.

Instead of referring to User directly, you should reference the user model using django.contrib.auth.get_user_model(). This method will return the currently active user model – the custom user model if one is specified, or User otherwise.

USER모델을 직접 참조하기 보다는 ‘get_user_model()’ 함수를 이용해서 참조하는것이 좋다.

When you define a foreign key or many-to-many relations to the user model, you should specify the custom model using the AUTH_USER_MODEL setting. For example:

user 모델을 재정의 하거나 FK, MTM관계를 가지고 있는것으로 정의했다면 settings.py에 있는 AUTH_USER_MODEL값을 설정해줘야한다. 사용방법은 아래와 같다.

from django.conf import settings
from django.db import models

class Article(models.Model):
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )

Specifying a custom user model

Keeping all user related information in one model removes the need for additional or more complex database queries to retrieve related models. On the other hand, it may be more suitable to store app-specific user information in a model that has a relation with your custom user model. That allows each app to specify its own user data requirements without potentially conflicting or breaking assumptions by other apps. It also means that you would keep your user model as simple as possible, focused on authentication, and following the minimum requirements Django expects custom user models to meet.

하나의 모델에 유저 모델을 모두 유지한다면 추가적인 DB쿼리는 필요가 없다. 하지만 유저정보를 다른 관계에 있는 커스텀 유저모델에 저장하는것이 좋다. 다른앱들과 충돌없이 각 앱의 특성에 맞게 구체화할 수 있기 때문이다.

The easiest way to construct a compliant custom user model is to inherit from AbstractBaseUser . AbstractBaseUser provides the core implementation of a user model, including hashed passwords and tokenized password resets. You must then provide some key implementation details:

class MyUser(AbstractBaseUser):
    identifier = models.CharField(max_length=40, unique=True)
    ...
    USERNAME_FIELD = 'identifier'

SCSS(SASS) - variable, nesting

|

SASS(SCSS)

Sass: Syntactically Awesome Style Sheets Ch02-01 Sass (SCSS) - 변수 (Variables) - YouTube

variable

$bg-color: red;


body {
    background-color: blanchedalmond;
}


#box1 {
    color: yellow;
    background-color: $bg-color;
    width: 100px;
}

nested

첫번 째

    <div id="box1">
        box1<br>
        <a href="#">button1</a>
        <div id="box2">
            box2 <br>
            <a href="#">buttton2</a>
        </div>
    </div>
  
  #box1 {
    font-size: 40px;
    background-color: #ffcccc;
    
    border-radius: 20px;
    border: 3px solid #f00;
    box-shadow: 0px 3px 11px 0px rgba(0, 0, 0, 0.75);

    & > a {
        color:blue;
        text-decoration: none;

        &:hover {
            color: #000;
            text-decoration: underline;
          }
      }
    &:hover {
        background-color: #ccc;
      } 

  }
  
  #box1 #box2 {
    font-size: 20px;
    background-color: #e9e9e9;
    
    border-radius: 20px;
    border: 3px solid #f00;
    box-shadow: 0px 3px 11px 0px rgba(0, 0, 0, 0.75);

    & > a {
        color: #ee6633;
        text-decoration: none;
        
        &:hover {
            color: #a22;
            text-decoration: underline;
          }
      }
  }
  

box2를 box1에 집어넣지 않은 이유는 가독성

두번 째

    <div id="box1">
        <div id="box1-title">box1 title</div>
        <a href="#">button1</a>
        <div id="box2">
            box2 <br>
            <a href="#">buttton2</a>
        </div>
    </div>

  #box1 {

	  &-title {
  	font-style: italic;
	    text-decoration: underline;
}

세번 째(중복되는 코드)

#box1 {
  border-radius: 20px;
  border: 3px solid #f00;

 &-title {
    border-radius: 20px;
    border: 3px solid #f00;
  }
}
#box1 {
  &, &-title {
    border-radius: 20px;
    border: 3px solid #f00;
  }
}

SCSS(SASS) - mixin, extend, import, if

|

mixin

@mixin fontSizeBgColor($size, $color) {
    font-size: $size;
    background-color: $color;
}

#box1 {
    // font-size: 40px;
    // background-color: #ffcccc;
    @include fontSizeBgColor(40px, #ffcccc)
}

extend

%boxshape { //#뒤에 붙이고 싶은 이름 
    border-radius: 20px;
    border: 3px solid #f00;
    box-shadow: 0px 3px 11px 0px rgba(0, 0, 0, 0.75);
}

#box1 {
	@extend #boxshape;
}

import

_filename -> compile안됨 underscore로 시작하는 파일은 컴파일이 안됨.

// _mixins.scss

@import mixins // 불러들일 때는 "_" 안쓴다. 

if

body {
    margin: 50px;
}

@mixin textandbgcolor($textcolor, $bgcolor) {
    color: $textcolor;
    background-color: $bgcolor;
}

@mixin theme($mood) {
    @if $mood == 'light' {
        @include textandbgcolor(#333333, #ffff00)
    }
    @else if $mood == 'dark' {
        @include textandbgcolor(#fff, #000000)
    }
    @else {
        @include textandbgcolor(#ff0000, #aaa)
    }
}

#box1 {
    @include theme('light')
}

#box2 {
    @include theme('dark')
}

#box3 {
    @include theme('light2')
}

Why use form tag in HTML?

|

Why use form tag

form태그 없이 충분히 데이터를 전송할 수 있는데 왜 쓰는지 궁금해서 검색해봤다.

stackoverflow

javascript - What is the purpose of the html form tag - Stack Overflow

Realistically, you can pretty much do whatever you want with HTML5 markup, and most browsers will parse it. Last time I checked, WebKit / Blink even allows pseudo-elements inside input elements , which is a clear violation of the spec - Gecko not so much. However, doing whatever you like with your markup will undoubtably invalidate it as far as semantics are concerned.

어떻게 하든지 상관은 없지만 semantics를 고려한다면 중요하다.

Meaning of semantic

The Importance of Semantics | The Classroom

Semantics is the study of the meaning of words and sentences. The discipline studies the interpretation of individual words, the construction of sentences and the literal interpretation of text the way it is written. Proper understanding of semantics relates to all academic disciplines in all languages, as a clear understanding allows students and teachers to communicate their messages clearly without fear of misinterpretation.

semantics는 단어와 문장의 의미에 관한 연구이다. 이는 각 단어의 해석, 문장의 구조, 글자가 쓰여진 그대로의 해석에 대한 연구이다.

Semantic web

what-is-the-semantic-web

The semantic web focuses on data rather than on documents, making it a much more immersive and detailed way of accessing information compared to the World Wide Web invented by Tim Berners Lee in the late 1980s.

문서 그 자체보다는 데이터에 집중한것이 semantic web이다.

According to the World Wide Web Consortium ( W3C ), the semantic web is “a common framework that allows data to be shared and reused across application, enterprise, and community boundaries”.

semantic web은 어떤 어플리케이션이든 기업이든 커뮤니티든 상관없이 데이터가 공유되고 재사용이 쉽도록 하는 framework(particular set of rules, ideas, or beliefs which you use in order to deal with problems)이다.

The concept is to offer people the information they’re looking for at the time they need it. One of its key philosophies is that although the information presented on the internet is useful, it’s not always needed at every point.

이런 생각은 사람들이 필요할 때 언제든 원하는 데이터를 제공할 수 있도록 해준다. 인터넷의 있는 정보들은 유용하지만 모든 정보들이 항상 필요한것은 아니기 때문이다.

The semantic web essentially allows for the connection of information using a network that can be easily read by machines – whether computers, IoT devices, mobile phones or other devices commonly used to access information.

semantic web은 컴퓨터, IoT기기, 스마트폰 등 어떤 기기를 사용하더라도 네트워크를 통해 쉽게 정보를 연결할 수 있도록 해준다.

It’s built on the premise that data within web pages is useful, but not in all circumstances. One of the biggest hurdles of the internet as it stands is that the majority of data is created using forms and there’s no unified way of publishing data so anyone can manage it. The way data is presented using HTML can be difficult to handle and so the semantic web takes the idea that if this data can be re-purposed, it’s more useful to everyone.

웹페이지에 있는 데이터는 유용하다는 전제를 깔고 간다. 하지만 모든 상황에서 그런것은 아니다. 가장 큰 문제는 데이터느느 form을 통해서 생성되고 이 데이터들은 통일된 관리 방법이나 관리자가 없다는 것이다. 표준없이 HTML을 구성한다면 데이터를 재사용하는데 어려움이 있을 것이다.그렇기 때문에 semantic web을 활용해 데이터가 재사용되기 쉽도록 했다.

The most important part of semantic web technologies is Resource Description Framework (RDF). This is a common framework for describing resources. It can represent metadata that can be parsed and processed by systems rather than just displayed to users.

semantic web에서 가장 중요한 기술은 RDF이다. 이것은 리소스를 묘사하는 방식이다. 사용자에게 눈으로 보여지는 화면보다는 시스템에 의해 분석될 수 있는 메타데이터를 나타낸다.

요약

방대한 양의 정보들이 machine에 의해 분석될 수 있도록 web을 구조화 하기 위한 프레임워크.

내 생각

비즈니스의 시작은 마케팅이라고 생각한다. 요즘 시대의 최고의 마케팅은 검색엔진에서 상위에 노출되는것이다. 그 이유는 광고비용이 따로 들지 않고, 무엇보다 여러 사람들에게 노출이 될 확률이 높아지기 때문이다. 검색엔진에 잘 노출되기 위해서는 여러가지 방법이 있을것이다. 그 중 하나가 semantic web이다.

Django Model option null, blank(string-based fields)

|

documentation

null

Model field reference | Django documentation | Django

If True, Django will store empty values as NULL in the database. Default is False.

Avoid using null on string-based fields such as CharField and TextField. If a string-based field has null=True, that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it’s redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL. One exception is when a CharField has both unique=True and blank=True set. In this situation, null=True is required to avoid unique constraint violations when saving multiple objects with blank values.

string-based fields인 charfield와 textfiled는 null을 사용하는것을 피해야한다. 만약 null값이 true라면 두가지 가능한 경우가 있다. null값과 ‘’ 빈 문자열. 장고에서는 널 값이 아닌 빈 문자열로 인식하는것이 convention 이다. 하나의 예외가 있다면 charfield가 unique=true, blank=true일 때 이다. 이 상황에서 빈 값이 있는 여러개의 객채를 저장할 때 unique constraint violations를 피하고 싶다면 null=true로 줘야한다.


PRIMARY KEY 제약 조건과 달리 UNIQUE 제약 조건에서는 NULL 값이 허용된다.. 단 UNIQUE 제약 조건에서 사용되는 다른 값과 마찬가지로 Null 값도 열당 하나만 허용된다.. UNIQUE 제약 조건은 FOREIGN KEY 제약 조건에서 참조할 수 있다.

출처 : UNIQUE 제약 조건 및 CHECK 제약 조건 Microsoft Docs


For both string-based and non-string-based fields, you will also need to set blank=True if you wish to permit empty values in forms, as the null parameter only affects database storage (see blank).

어떤 경우에서든 빈 값을 입력받고 싶다면 blank=True로 설정해줘야한다.

blank

Model field reference

If True, the field is allowed to be blank. Default is False.

Note that this is different than null. null is purely database-related, whereas blank is validation-related. If a field has blank=True, form validation will allow entry of an empty value. If a field has blank=False, the field will be required.

blank는 null과는 다르다. null은 database와 관련된것에 비해 blank는 유효성을 검사하는 용도이다. blank=true라면 빈값에 대해서 form validation을 통과할 것이다.

stackoverflow

1

python - differentiate null=True, blank=True in django - Stack Overflow

CHAR and TEXT types are never saved as NULL by Django, so null=True is unnecessary. However, you can manually set one of these fields to None to force set it as NULL. If you have a scenario where that might be necessary, you should still include null=True.

models.DateTimeField(blank=True) #*raises IntegrityError if blank*

models.DateTimeField(null=True) #*NULL allowed, but must be filled out in a form*

Obviously those two options don’t make logical sense to use (though, there might be a use case for null=True, blank=False if you want a field to always be required in forms, but optional when dealing with an object through something like the shell.)

models.CharField(blank=True) #*No problem, blank is stored as ''*

models.CharField(null=True) #*NULL allowed, but will never be set as NULL*

CHAR and TEXT types are never saved as NULL by Django, so null=True is unnecessary. However, you can manually set one of these fields to None to force set it as NULL. If you have a scenario where that might be necessary, you should still include null=True.

장고에서 char, text는 절대 null로 저장되지 않는다. 강제로 null로 지정해야 한다면 null=true로 지정해야한다.

2

null=False, blank=False

This is the default configuration and means that the value is required in all circumstances.

null=True, blank=True

This means that the field is optional in all circumstances. (As noted below, though, this is not the recommended way to make string-based fields optional.)

string-based fields에는 적합하지 않은 옵션이다.

null=False, blank=True

This means that the form doesn’t require a value but the database does. There are a number of use cases for this:

form에 값을 입력하지 않지만 데이터베이스에서는 값이 필요한 경우이다. 몇몇 사용예는 다음과 같다.

The most common use is for optional string-based fields. As noted in the documentation, the Django idiom is to use the empty string to indicate a missing value. If NULL was also allowed you would end up with two different ways to indicate a missing value.

장고에서는 빈 문자열로 누락된 값을 나타낸다. 만약 null이 허용된다면 결측값에 대해 두가지 의미를 가지게 된다. 모호해지게된다.

Another common situation is that you want to calculate one field automatically based on the value of another (in your save() method, say). You don’t want the user to provide the value in a form (hence blank=True), but you do want the database to enforce that a value is always provided (null=False).

유저가 입력하는 것이 아니라 개발자가 원하는 값으로 넣고 싶은경우. (ex. 글 작성한 시간, 회원가입 날짜)

Another use is when you want to indicate that a ManyToManyField is optional. Because this field is implemented as a separate table rather than a database column, null is meaningless. The value of blank will still affect forms, though, controlling whether or not validation will succeed when there are no relations.

null=True, blank=False

This means that the form requires a value but the database doesn’t. This may be the most infrequently used configuration, but there are some use cases for it:

이런 경우는 잘 없다.

It’s perfectly reasonable to require your users to always include a value even if it’s not actually required by your business logic. After all, forms are only one way of adding and editing data. You may have code that is generating data which doesn’t need the same stringent validation that you want to require of a human editor.

Another use case that I’ve seen is when you have a ForeignKey for which you don’t wish to allow cascade deletion. That is, in normal use the relation should always be there (blank=False), but if the thing it points to happens to be deleted, you don’t want this object to be deleted too. In that case you can use null=True and on_delete=models.SET_NULL to implement a simple kind of soft deletion.