코딩 개발일지

프로필사진 업로드 / 팔로우 기능 에러해결 본문

AI 본 교육/AI 9주차

프로필사진 업로드 / 팔로우 기능 에러해결

호기호 2023. 10. 10. 16:22

팀프로젝트 2일차에 여러 기능을 만들다가 문제에 발생했다.

 

1. 프로필사진 업로드를 하고, admin 페이지에서 user생성할 때, 사진 업로드 칸이 없다.

 

2. 회원가입 시, 프로필사진 업로드 후 가입하면, 로그인할때, 오류 발생함.

    (지정된 자격 증명에 해당하는 활성화된 사용자를 찾을 수 없습니다)

 

3. 팔로우 기능 추가 후, user profile 페이지에서 followers, followings 둘 다 표기하고 싶었지만, followings만 나오는 문제


1. 프로필사진 업로드를 하고, admin 페이지에서 user생성할 때, 사진 업로드 칸이 없다.

 

 우리는 user model을 만들 때,

django 기본 내장 user는 AbstractUser 인데, 커스텀하고싶어서  AbstractBaseUser를 이용했다.

 

따라서, admin.py에서도 따로 custom을 하기위해 공식문서에서 custom example을 가져와서 고쳐썻다.

class UserCreationForm(forms.ModelForm):
    """A form for creating new users. Includes all the required
    fields, plus a repeated password."""
    password1 = forms.CharField(label="Password", widget=forms.PasswordInput)
    password2 = forms.CharField(
        label="Password confirmation", widget=forms.PasswordInput
    )
   
    class Meta:
        model = User
        fields = ["email",]

user 생성 폼이 이렇게 되어있어서

class UserCreationForm(forms.ModelForm):
    """A form for creating new users. Includes all the required
    fields, plus a repeated password."""
    nickname = forms.CharField(max_length=100)
    image = forms.ImageField(required=False)
    password1 = forms.CharField(label="Password", widget=forms.PasswordInput)
    password2 = forms.CharField(
        label="Password confirmation", widget=forms.PasswordInput
    )
   
    class Meta:
        model = User
        fields = ["email", "nickname","image"]

이렇게 nickname과 image를 넣어줬는데, admin 페이지에서 안보였다.

 

해결법은 class UserAmdmin 에서 list_display와 add_fieldsets에도 추가를 해줘야 보이는 것이었다.

class UserAdmin(BaseUserAdmin):
    # The forms to add and change user instances
    form = UserChangeForm
    add_form = UserCreationForm

    # The fields to be used in displaying the User model.
    # These override the definitions on the base UserAdmin
    # that reference specific fields on auth.User.
    list_display = ["email", "is_admin", "nickname","image"]
    list_filter = ["is_admin"]
    fieldsets = [
        (None, {"fields": ["email", "password","follower"]}),
        ("Personal info", {"fields": ["nickname","image"]}),
        ("Permissions", {"fields": ["is_admin"]}),
    ]
    # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
    # overrides get_fieldsets to use this attribute when creating a user.
    add_fieldsets = [
        (
            None,
            {
                "classes": ["wide"],
            "fields": ["email", "password1", "password2", "nickname","image"],
            },
        ),
    ]
    search_fields = ["email"]
    ordering = ["email"]
    filter_horizontal = []

2. 회원가입 시, 프로필사진 업로드 후 가입하면, 로그인할때, 오류 발생함.

    (지정된 자격 증명에 해당하는 활성화된 사용자를 찾을 수 없습니다)

 

admin 페이지에서 프로필 사진 업로드 후 user를 생성하고 postman에서 login을 하면 로그인이 정상적으로 잘 되고,

 

postman에서 form-data에서 프로필 사진 업로드 후 회원가입을 하고, postman에서 login을 하면 에러가 발생했다.

에러 : (지정된 자격 증명에 해당하는 활성화된 사용자를 찾을 수 없습니다)

웃긴 점은, 프로필 사진을 올리지않고, Body 부분에서 raw > JSON 으로 작성하면 정상 로그인이 된다는 것이다.

 

오랜 고민과 갖가지 실험을 해본 결과, 데이터베이스에서 form-data로 프로필 업로드해서 만든 user는 is_active가 0 으로 되어있는 것을 발견했다.

팀장님의 vscode에서만 데이터베이스가 생성되다보니, 찾는데 오래 걸린 것 같다.

그래서 form-data에서 is_active를 1로 변경해서 user를 만들었더니 해결됐다.

 


3. 팔로우 기능 추가 후, user profile 페이지에서 followers, followings 둘 다 표기하고 싶었지만, followings만 나오는 문제

 

팔로우 기능을 user model에 만들어줬다.

followings = models.ManyToManyField('self',related_name="following", blank=True, symmetrical=False)

이렇게 만들어주고, 프로필 serializer에 두 개를 추가해줬다.

class UserProfileSerializer(serializers.ModelSerializer):
    followers =serializers.StringRelatedField(many=True)
    followings =serializers.StringRelatedField(many=True)
 
    class Meta:
        model = User
        fields = ("id","email","followings", "followers")

근데, followings는 나오는데 followers는 안나왔다.

 

해결방법은

followings를 ManyToMany필드로 받고,'self'로 쓰면, from, to 로 데이터베이스에 생성이 되서 related_name을 followers로 해줘야 했다.

followings = models.ManyToManyField('self',related_name="followers", blank=True, symmetrical=False)

바꿔주니 해결 완료.

self ManyToMany 를 제대로 이해하지 못해서 생긴 문제였다.