ポストページとポスト編集

10449 ワード

モードパイ
from django.db import models
from django.contrib.auth.models import User

class Post(models.Model):
    title = models.CharField(max_length=30)
    body = models.TextField(max_length=500)
    date_posted = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title
ラン端子
> python manage.py makemigrations
> python manage.py migrate
フォーム.パイ
class postForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['title', 'body', ]
VIESパイ
from .forms import  postForm,
from django.contrib.auth.forms import User

def postPage(request):
    if request.method == 'POST':
        form = postForm(request.POST)
        if form.is_valid():
            title = request.POST.get('title')
            body = request.POST.get('body')
            user = User.objects.filter(username=request.user.username).first()
            post = Post.objects.create(title=title, body=body, author=user)
            post.save()
            return redirect('home')
    else:
        form = postForm()

    return render(request, 'app/post.html', {'form': form})
ポスト.HTML
{% load crispy_forms_tags %}
{% block content %}
    <form method="POST">
    {% csrf_token %}
    {{ form|crispy }}<br>
    <button type="submit">Post</button>
    </form>
{% endblock %}
URL.パイ
from django.urls import path
from . import views

urlpatterns = [

    path('post/',views.postPage,name='post'),

]
ポストフォーザポスト
ビューパイ
from .models import Post

def homePage(request):
    posts = Post.objects.all()
    return render(request, 'app/home.html', {'posts': posts})
ホーム.HTML
{% block content %}
    {% for post in posts %}
        <article class="media content-section">
          <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}">
          <div class="media-body">
            <div class="article-metadata">
              <a class="mr-2" href="#">{{ post.author }}</a>
              <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small>
            </div>
            <h2><a class="article-title" href="{% url 'Postview' post.id %}">{{ post.title }}</a></h2>
            <p class="article-content">{{ post.body }}</p>
          </div>
        </article>
    {% endfor %}
{% endblock content %}