회원가입 시 one-to-one 방식으로 모델 확장해보았는데 자꾸 오류나네요ㅠㅠ

common/forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from common.models import Profile


class UserForm(UserCreationForm):
    email = forms.EmailField(label="이메일")

    class Meta:
        model = User
        fields = ("username", "email")


class ProfileForm(forms.ModelForm):
    rank = forms.IntegerField(label="기수")
    sq = forms.IntegerField(label="중대")
    name = forms.CharField(label="이름", max_length=20)

    class Meta:
        model = Profile
        fields = ("rank", "sq", "name")

common/models.py

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver


class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    rank = models.IntegerField()
    sq = models.IntegerField()
    name = models.CharField(max_length=20)


@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)


@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

common/admin.py

from django.contrib import admin
from .models import Profile

admin.site.register(Profile)

common/views.py

from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from common.forms import UserForm, ProfileForm


def signup(request):
    if request.method == "POST":
        user_form = UserForm(request.POST)
        profile_form = ProfileForm(request.POST)
        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            username = user_form.cleaned_data.get('username')
            raw_password = user_form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            login(request, user)
            return redirect('index')
    else:
        user_form = UserForm()
        profile_form = ProfileForm()
    return render(request, 'common/signup.html',
                  {'user_form': user_form, 'profile_form': profile_form})

common/login.html

{% extends "base.html" %}
{% block content %}
<div class="container my-3">
    <div class="row">
        <div class="col-4">
            <h4>로그인</h4>
        </div>
        <div class="col-8 text-right">
            <span><a href="{% url 'common:signup' %}">회원가입</a></span>
        </div>
    </div>
    <form method="post" class="post-form" action="{% url 'common:login' %}">
        {% csrf_token %}
        {% include "form_errors.html" %}
        <div class="form-group">
            <label for="username">교번</label>
            <input type="text" class="form-control" name="username" id="username"
                   value="{{ form.username.value|default_if_none:'' }}">
        </div>
        <div class="form-group">
            <label for="password">비밀번호</label>
            <input type="password" class="form-control" name="password" id="password"
                   value="{{ form.password.value|default_if_none:'' }}">
        </div>
        <button type="submit" class="btn btn-warning">로그인</button>
    </form>
</div>
{% endblock %}

common/signup.html

{% extends "base.html" %}
{% block content %}
<div class="container my-3">
    <div class="row my-3">
        <div class="col-4">
            <h4>회원가입</h4>
        </div>
        <div class="col-8 text-right">
            <span>또는 <a href="{% url 'common:login' %}">로그인 하세요.</a></span>
        </div>
    </div>
    <form method="post" class="post-form">
        {% csrf_token %}
        {% include "form_errors.html" %}
        <div class="form-group">
            <label for="username">교번</label>
            <input type="text" class="form-control" name="username" id="username"
                   value="{{ form.username.value|default_if_none:'' }}">
        </div>
        <div class="form-group">
            <label for="rank">기수</label>
            <input type="number" class="form-control" name="rank" id="rank"
                   value="{{ form.rank.value|default_if_none:'' }}">
        </div>
        <div class="form-group">
            <label for="sq">중대</label>
            <input type="number" class="form-control" name="sq" id="sq"
                   value="{{ form.sq.value|default_if_none:'' }}">
        </div>
        <div class="form-group">
            <label for="name">이름</label>
            <input type="text" class="form-control" name="name" id="name"
                   value="{{ form.name.value|default_if_none:'' }}">
        </div>
        <div class="form-group">
            <label for="password1">비밀번호</label>
            <input type="password" class="form-control" name="password1" id="password1"
                   value="{{ form.password1.value|default_if_none:'' }}">
        </div>
        <div class="form-group">
            <label for="password2">비밀번호 확인</label>
            <input type="password" class="form-control" name="password2" id="password2"
                   value="{{ form.password2.value|default_if_none:'' }}">
        </div>
        <div class="form-group">
            <label for="email">이메일</label>
            <input type="text" class="form-control" name="email" id="email"
                   value="{{ form.email.value|default_if_none:'' }}">
        </div>
        <button type="submit" class="btn btn-warning">생성하기</button>
    </form>
</div>
{% endblock %}

localhost:8000/admin을 요청하면
RelatedObjectDoesNotExist at /admin/login/
User has no profile.
이렇게 오류가 떠요.

그리고 회원가입 시에도 자꾸 오류가 나는데
어디서부터 잘못된 걸까요?ㅠㅠ

miso 52

2021년 5월 27일 1:49 오전

목록으로
1개의 답변이 있습니다. 1 / 1 Page

안녕하세요.

Profile 모델에 User 모델이 연결되어 있는데 profile_form.save() 시에 User가 설정이 안되어서 회원가입이 안될것 같네요.
profile = profile_form.save(commit=False) 로 한 다음에 다시 profile.user = user 이런 식으로 user를 다시 대입한 후 profile.save() 로 저장해 주어야 할 듯합니다.

박응용

2021년 5월 27일 8:17 오전