Django

[Django] 12. Django ModelForm

개발자 뭄뭄 2022. 10. 5. 22:01
반응형

1. Django ModelForm


  • ModelForm : DB의 구조인 Model == 사용자에게 입력받는 Form 일 때 사용한다.
    • ex) 회원가입
  • Form : DB에 저장할 필요가 없을 때!
    • ex) 로그인
  • 참조할 model Class를 models.py에서 가지고 온다.
from django import forms
from .models import Article

class ArticleForm(forms.ModelForm):
    class Meta:
        model = Article
        fields = '__all__'
  • 인스턴스를 만드는 것이 아니라, 함수 자체가 필요하다! 필요할 때 호출하기 위해서 그대로 가져오는 것이다.
  • Meta는 데이터를 위한 데이터 작성을 위해서 쓴다.
    • 파이썬의 문법적 개념으로 접근하지 말고 그냥 그렇구나~ 하고 사용하자.

2. CREATE


  • articles/urls.py
    from django.urls import path
    from . import views
    
    app_name = "articles"
    urlpatterns = [
        path("", views.index, name="index"),
    		# 이 부분을 추가한다.
        path("create/", views.create, name="create"),
    ]
  • articles/views.py
    from django.shortcuts import render, redirect
    from .forms import ArticleForm
    from .models import Article
    
    # Create your views here.
    
    def index(request):
        articles = Article.objects.all()
        context = {
            'articles':articles
        }
        return render(request, "articles/index.html", context)
    
    def create(request):
        # 작성했을 때, index 페이지로 이동
        if request.method == "POST":
            form = ArticleForm(request.POST)
            if form.is_valid():
                form.save()
                return redirect("articles:index")
        # 단순히 create 링크로 들어왔을 때, form을 보여줄 곳
        else:
            form = ArticleForm()
        context = {
            'form':form
        }
        return render(request, 'articles/create.html', context)
  • articles/templates/create.html
    {% extends 'base.html' %}
    
    {% block content %}
        <h1>CREATE</h1>
        <hr>
        <form action="{% url 'articles:create' %}" method="POST">
            {% csrf_token %}
            {{ form.as_p  }}
            <input type="submit">
        </form>
    {% endblock content %}
  • articles/templates/index.html
    {% extends 'base.html' %}
    
    {% block content %}
        <h1>INDEX</h1>
        <a href="{% url 'articles:create'%}">[NEW]</a>
        <hr>
        {% for article in articles%}
            <p>글 번호 : {{article.pk}}</p>
            <p>작성자 : {{article.user}}</p>
            <p>내용 : {{article.context}}</p>
            <hr>
        {% endfor %}
    {% endblock content %}

3. Detail


  • articles/urls.py
    from django.urls import path
    from . import views
    
    app_name = "articles"
    urlpatterns = [
        path("", views.index, name="index"),
        path("create/", views.create, name="create"),
    		# 이부분을 추가하였습니다.
        path("<int:pk>/", views.detail, name="detail"),
    ]
  • articles/views.py
    def detail(request, pk):
        article = Article.objects.get(pk=pk)
        context = {
            'article':article
        }
        return render(request, 'articles/detail.html', context)
  • articles/templates/index.html
    <a href="{% url 'articles:detail' article.pk %}">[DETAIL]</a>
  • articles/templates/detail.html
    {% extends 'base.html' %}
    
    {% block content %}
        <h1>DETAIL</h1>
        <h2>{{article.pk}}번째 글</h2>
        <hr>
        <p>작성자 : {{article.user}}</p>
        <p>내용 : {{article.context}}</p>
        <p>작성시각 : {{article.created_at}}</p>
        <p>수정시각 : {{article.updated_at}}</p>
    
        <a href="{% url 'articles:index' %}">[뒤로가기]</a>
        {% endblock content %}

cf) 사용자가 경로에 없는 페이지를 요청할 시에 (404) 를 띄우는 방법

  • django shortcut 에서 get_object_or_404를 불러온다.
    # articles/views.py
    
    from django.shortcuts import render, redirect, get_object_or_404
    def detail(request, pk):
    		# 이 부분을 수정하면 된다.
        article = get_object_or_404(Article, pk=pk)
        context = {
            'article':article
        }
        return render(request, 'articles/detail.html', context)

4. DELETE


  • articles/urls.py
    path("<int:pk>/delete/", views.delete, name="delete"),
  • articles/views.py
    def delete(request, pk):
        article = get_object_or_404(Article, pk=pk)
        article.delete()
        return redirect('articles:index')
  • articles/templates/detail.html
    {% extends 'base.html' %}
    
    {% block content %}
        <h1>DETAIL</h1>
        <h2>{{article.pk}}번째 글</h2>
        <hr>
        <p>작성자 : {{article.user}}</p>
        <p>내용 : {{article.context}}</p>
        <p>작성시각 : {{article.created_at}}</p>
        <p>수정시각 : {{article.updated_at}}</p>
    
        <a href="{% url 'articles:index' %}">[뒤로가기]</a>
        <form action="{% url 'articles:delete' article.pk %}" method="POST">
            {% csrf_token %}
            <input type="submit" value="삭제">
        </form>
        {% endblock content %}

5. UPDATE



Uploaded by N2T

반응형

'Django' 카테고리의 다른 글

[Django] 14. Authentication with User  (0) 2022.10.05
[Django] 13. Cookie & Session  (1) 2022.10.05
[Django] 11. Django authentication system  (0) 2022.09.22
[Django] 10. DJANGO FORM  (0) 2022.09.21
[Django] 9. CRUD with functions  (1) 2022.09.21