Backend/Django

django 19. Profileapp 구현 시작

meong_j 2021. 10. 6. 17:31
728x90
반응형

DB 반영하기

  • 생성한 model 마이그레이션(migration)해서 db에 반영하기

 

 

views.py

from django.shortcuts import render

# Create your views here.
from django.urls import reverse_lazy
from django.views.generic import CreateView

from profileapp.forms import ProfileCreationForm
from profileapp.models import Profile


class ProfileCreateView(CreateView):
    model = Profile
    context_object_name = 'target_profile'
    form_class = ProfileCreationForm
    success_url = reverse_lazy('accountapp:hello_world')
    template_name = 'profileapp/create.html'

    def form_valid(self, form):
        temp_profile = form.save(commit=False)
        temp_profile.user = self.request.user
        temp_profile.save()
        return super().form_valid(form)
  • form_valid 함수 생성, form에서 user정보 가져오지 않아서 작업
  • temp_profile = form.save(commit=False) : temp_profile 변수에 form 데이터 가져와서 임시저장
  • temp_profile.user = self.request.user : temp_profile의 user 정보를 당사자인 user로 request보냄
  • temp_profile.save()  : 정상적으로 저장
  • super().form_valid(form) : 작성한 form 리턴

 

 

 

detail.html

{% extends 'base.html' %}
{% load bootstrap4 %}

{% block content %}

<div>
    <div style="text-align: center; max-width: 500px; margin: 4rem auto;">
        <p>
            <!-- 가입 시간 -->
            {{ target_user.date_joined }}
        </p>

        {% if target_user.profile %}
         <h2 style="font-family: NanumBarunpenB">
            {{ target_user.profile.nickname }}
        </h2>
        {% else %}
        <a href="{% url 'profileapp:create' %}">
            <h2 style="font-family: NanumBarunpenB">
                Create Profile
            </h2>
        </a>
        {% endif %}

        {% if target_user == user %}
        <a href="{% url 'accountapp:update' pk=user.pk %}">
            <p>
                Change Info
            </p>
        </a>
        {% endif %}

        {% if target_user == user %}
        <a href="{% url 'accountapp:delete' pk=user.pk %}">
            <p>
                Quit
            </p>
        </a>
        {% endif %}

    </div>

</div>

{% endblock %}
  • 유저가 profile 생성했으면 nickname 출력, 생성하지 않았으면 Create profile 링크 연결 

 

create.html

{% extends 'base.html' %}
{% load bootstrap4 %}

{% block content %}

<div style="text-align:center;  max-width: 500px; margin: 4rem auto">
    <div class="mb-4">
        <h4>Profile Create</h4>
    </div>
    <form action="{% url 'profileapp:create' %}"  method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {% bootstrap_form form %}
        <input type="submit" class="btn btn-dark rounded-pill col-6 mt-3">
    </form>
</div>


{% endblock %}
  • 이미지, 닉네임, 메시지 입력하는 form 페이지 구현

 

 

  • 로그인 후 Profile 미등록한 유저의 detail화면

 

  • Profile 등록 페이지 화면

 

 

  • 생성된 nickname 출력 확인
반응형