現在djangoをつかって簡単なSNSアプリを作成しており、ただいまユーザーごとのページを制作しているのですが、ページにそのユーザーの過去の投稿の情報を表示できるようにしたいです。表示したい情報は主に投稿のタイトル、投稿日時、タグで、表示順は投稿日が新しいものから降順にしたいです。
コードは一応組んでみたのですが、ユーザーページに過去の投稿がうまく反映されていない状態となっております。
有識者の方、ご教授願います。
・ユーザーページのHTMLファイル
{% extends 'base.html' %} {% block body %} {% load static %} <div class="container"> <h1>My page</h1> <hr> <div class="row"> <div class="col"><h4>■ 登録情報</h4></div> </div> <p>ユーザー名 : {{ user.username }}</p> <p>過去の投稿</p> <div class="user_article"> {% for list in object_list %} <a href="{% url 'main:article_detail' user.pk %}">{{ list.title }}</a> {% endfor %} </div> </div> {% endblock body %}
・views.py
from django.contrib.auth.views import LoginView, LogoutView from django.views.generic import TemplateView, DetailView, ListView, CreateView from .forms import LoginForm, TrvFrm, SignupForm from .models import TravelForm from django.views import View from django.shortcuts import redirect from django.urls import reverse_lazy from django.contrib.auth.models import User from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin # Create your views here. class IndexView(ListView): template_name = 'index.html' model = TravelForm ordering = ['-date'] class ArticleCreate(CreateView): form_class = TrvFrm template_name = 'article_form.html' success_url = reverse_lazy('main:complete_pub') class ArticlePub(TemplateView): template_name = 'complete_pub.html' class ArticleDetail(DetailView): models = TravelForm template_name = 'article_detail.html' context_object_name = 'object' queryset = TravelForm.objects.all() class ArticleList(ListView): template_name = 'article_list.html' model = TravelForm ordering = ['-date'] class Login(LoginView): form_class = LoginForm template_name = 'login.html' class Logout(LogoutView): template_name = 'logout.html' class OnlyYouMixin(UserPassesTestMixin): raise_exception = True def test_func(self): user = self.request.user return user.pk == self.kwargs['pk'] '''マイページ''' class MyPage(OnlyYouMixin, DetailView): model = User template_name = 'my_page.html' class MyPageList(LoginRequiredMixin, ListView): model = TravelForm ordering = ['-date'] template_name = 'my_page.html' def get_queryset(self): return TravelForm.objects.filter(user=self.request.user) '''サインアップ''' class Signup(CreateView): template_name = 'user_form.html' form_class =SignupForm def form_valid(self, form): user = form.save() # formの情報を保存 return redirect('main:signup_done') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["process_name"] = "Sign up" return context '''サインアップ完了''' class SignupDone(TemplateView): template_name = 'signup_done.html'
・forms.py
from django import forms from .models import TravelForm from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import get_user_model from django.contrib.auth.forms import AuthenticationForm, UserCreationForm class TrvFrm(forms.ModelForm): class Meta: model = TravelForm fields = ('title', 'author', 'tags', 'place', 'image', 'place2', 'image2', 'place3', 'image3', 'place4', 'image4', 'place5', 'image5', 'place6', 'image6', 'place7', 'image7', 'place8', 'image8', 'text', ) User = get_user_model() '''ログイン用フォーム''' class LoginForm(AuthenticationForm): # bootstrap4対応 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs['class'] = 'form-control' field.widget.attrs['placeholder'] = field.label '''サインアップ用フォーム''' class SignupForm(UserCreationForm): class Meta: model = User fields = ('last_name', 'first_name', 'email','username', ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs['class'] = 'form-control' field.widget.attrs['required'] = '' # 全フィールドを入力必須 # オートフォーカスとプレースホルダーの設定 print(field.label) if field.label == '姓': field.widget.attrs['autofocus'] = '' # 入力可能状態にする field.widget.attrs['placeholder'] = '田中' elif field.label == '名': field.widget.attrs['placeholder'] = '一郎' elif field.label == 'メールアドレス': field.widget.attrs['placeholder'] = '***@gmail.com'
・models.py
from django.db import models from django.utils import timezone from django.contrib.auth import get_user_model from django.contrib.auth.models import User from taggit.managers import TaggableManager import uuid from taggit.managers import TaggableManager from taggit.models import GenericUUIDTaggedItemBase, TaggedItemBase class UUIDTaggedItem(GenericUUIDTaggedItemBase, TaggedItemBase): class Meta: verbose_name = ("Tag") verbose_name_plural = ("Tags") class TravelForm(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) date = models.DateTimeField(default=timezone.now) tags = TaggableManager(blank=True, through=UUIDTaggedItem) title = models.CharField(verbose_name='タイトル', max_length=30, default='', null=False) place = models.CharField(verbose_name='1か所目', max_length=50, default='', null=False) image = models.ImageField(upload_to='images/', verbose_name="1か所目の画像", null=True, blank=True) place2 = models.CharField(verbose_name='2か所目', max_length=50, default='', null=True, blank=True) image2 = models.ImageField(upload_to='images/', verbose_name='2か所目の画像', null=True, blank=True) place3 = models.CharField(verbose_name='3か所目', max_length=50, default='', null=True, blank=True) image3 = models.ImageField(upload_to='images/', verbose_name='3か所目の画像', null=True, blank=True) place4 = models.CharField(verbose_name='4か所目', max_length=50, default='', null=True, blank=True) image4 = models.ImageField(upload_to='images/', verbose_name='4か所目の画像', null=True, blank=True) place5 = models.CharField(verbose_name='5か所目', max_length=50, default='', null=True, blank=True) image5 = models.ImageField(upload_to='images/', verbose_name='5か所目の画像', null=True, blank=True) place6 = models.CharField(verbose_name='6か所目', max_length=50, default='', null=True, blank=True) image6 = models.ImageField(upload_to='images/', verbose_name='6か所目の画像', null=True, blank=True) place7 = models.CharField(verbose_name='7か所目', max_length=50, default='', null=True, blank=True) image7 = models.ImageField(upload_to='images/', verbose_name='7か所目の画像', null=True, blank=True) place8 = models.CharField(verbose_name='8か所目', max_length=50, default='', null=True, blank=True) image8 = models.ImageField(upload_to='images/', verbose_name='8か所目の画像', null=True, blank=True) text = models.TextField(verbose_name='感想やおすすめの楽しみ方など', default='', null=False)
あなたの回答
tips
プレビュー