상세 컨텐츠

본문 제목

prfileapp 구현 시작

django

by 개복신 개발자 2021. 9. 23. 21:01

본문

728x90
반응형

앞서 만든 모델을 적용하기 위해서 migrate를 하자

python manage.py makemigrations

python manage.py migrate


views.py작성

클래스 기반으로 작성

class ProfileCreateView(CreateView):
    model = Profile					# 연결할 클래스 or table명
    context_object_name = 'target_profile' # context 변수명 지정
    form_class = ProfileCreationForm # 우리가 만든 폼 클래스를 form_class에 할당!
    success_url = reverse_lazy('accountapp:hello_world')	# 성공시 연결할 페이지
    template_name = 'profileapp/create.html'				# 구현할 Template

-Profile 클래스를 models.py에서 가져옴


template 작성

profileapp/templates/profileapp/create.html

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

{% block content %}
<div style="text-align: center; max-width: 500px; margin: 4rem auto;">
    <div class="mb-4"><!--margin-bottom=mb-->
        <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 %}

**이미지 파일을 다룰 때 enctype

  1. application/www-form-urlencoded
    -->디폴트값enctype을 따로 설정하지 않으면 이 값이 설정. 폼데이터는 서버로 전송되기 전에 URL-Encode로 됨.
  2. multipart/form-data   -->파일이나 이미지를 서버로 전송할 경우 이 방식을 사용.
  3. text/plain -->이 형식은 인코딩을 하지 않은 문자 상태로 전송.

urls 설정

from django.urls import path

from .views import *

app_name = 'profileapp'

urlpatterns = [
    path('create/', ProfileCreateView.as_view(), name='create'),

]

accountapp의 detail.html에 우리가 설정한 닉네임이 이름 대신에 뜨도록 설정해보자

{% extends 'base.html' %}

{% block content %}

<div>
    <div style="text-align: center; max-width: 500px; margin:4rem auto;">
        <p>
            {{target_user.data_joined}}
        </p>
        {% if target_user.profile %}
        <h2>
            {{target_user.profile.nickname}}
        </h2>
        {% else %}
        <a href="{% url 'profileapp:create' %}">
        <h2>
            Create Profile
        </h2>
        </a>
        {% endif %}


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

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

-target_user

context_object_name = 'target_user'-->views.py에서 설정한 코드


이를 토대로 runserver하면 오류가 발생한다.

IntegrityError at /profiles/create/ NOT NULL constraint failed:

 

결론적으로 이 오류를 해결하기 위해서 form_valid 메소드를 ProfileCreateView에서 정의해주어야 한다.

from django.urls import reverse_lazy
from django.views.generic import CreateView

from .forms import ProfileCreationForm
from .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)
반응형

'django' 카테고리의 다른 글

detail 페이지 오답노트  (0) 2022.03.21
admin  (0) 2022.03.21
profileapp 시작 그리고 ModelForm  (0) 2021.09.22
Decorater를 이용한 코드 간소화  (0) 2021.09.22
Authentication 인증 시스템 구축  (0) 2021.09.22

관련글 더보기

댓글 영역