(Django 기초) articleapp 구현 - Create

Posted by : at

Category : Django



# articleapp\models.py

class Article(models.Model):
    writer = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='article', null=True)
    title = models.CharField(max_length=200, null=True)
    image = models.ImageField(upload_to='article/', null=True)
    content = models.TextField(null=True)
    created_at = models.DateField(auto_now_add=True, null=True)
# articleapp\forms.py

class ArticleCreationForm(ModelForm):
    class Meta:
        model = Article
        fields = ['title', 'image', 'content']
$ python manage.py makemigrations
$ python manage.py migrate
# articleapp\views.py

@method_decorator(login_required, 'get')
@method_decorator(login_required, 'post')
class ArticleCreateView(CreateView):
    model = Article
    form_class = ArticleCreationForm
    template_name = 'articleapp/create.html'

    def form_valid(self, form):
        temp_article = form.save(commit=False)
        temp_article.writer = self.request.user
        temp_article.save()
        return super().form_valid(form)

    def get_success_url(self):
        return reverse('articleapp:detail', kwargs={'pk': self.object.pk})


class ArticleDetailView(DetailView):
    model = Article
    context_object_name = 'target_article'
    template_name = 'articleapp/detail.html'
<!-- articleapp\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>Article Create</h4>
        </div>
        <form action="{% url 'articleapp: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 %}
<!-- articleapp\detail.html -->

{% extends 'base.html' %}

{% block content %}

    <div style="text-align: center; max-width: 500px; margin: 4rem auto">
        <h1>
            {{ target_article.title }}
        </h1>

        <img src="{{ target_article.image.url }}" alt="">

        <p>
            {{ target_article.content }}
        </p>

    </div>

{% endblock %}
<!-- header.html -->

<div class="pragmatic_header"> 
    <div> 
        <h1 class="pragmatic_logo">Pragmatic</h1> 
    </div> 
    <div> 
        <a href="{% url 'articleapp:list' %}"> 
            <span>Articles</span> 
        </a> 
        <span>nav</span> 
        {% if not user.is_authenticated %} 
        <a href="{% url 'accountapp:login' %}?next={{ request.path }}"> 
            <span>login</span> 
        </a> 
        <a href="{% url 'accountapp:create' %}"> 
            <span>SignUp</span> 
        </a> 
        {% else %} 
        <a href="{% url 'accountapp:logout' %}?next{{ request.path }}"> 
            <span>logout</span> 
        </a> 
        <a href="{% url 'accountapp:detail' pk=user.pk %}"> 
            <span> MyPAge</span> 
        </a> 
        {% endif %} 
    </div> 
</div>
# articleapp\urls.py

app_name = 'articleapp'

urlpatterns = [
    path('list/', TemplateView.as_view(template_name='articleapp/list.html'), name='list'),

    path('create/', ArticleCreateView.as_view(), name='create'),
    path('detail/<int:pk>', ArticleDetailView.as_view(), name='detail'),
]
<!-- articleapp\list.html -->

<!-- ... -->

    <div style="text-align:center;">
        <a href="{% url 'articleapp:create' %}" class="btn btn-dark rounded-pill col-3 mt-3 mb-3">
            Create Article
        </a>
    </div>

  <script src="{% static 'js/magic-grid.js' %}"></script>

{% endblock %}


About Taehyung Kim

안녕하세요? 8년차 현업 C++ 개발자 김태형이라고 합니다. 😁 C/C++을 사랑하며 다양한 사람과의 협업을 즐깁니다. ☕ 꾸준한 자기개발을 미덕이라 생각하며 노력중이며, 제가 얻은 지식을 홈페이지에 정리 중입니다. 좀 더 상세한 제 이력서 혹은 Private 프로젝트 접근 권한을 원하신다면 메일주세요. 😎

Star
Useful Links