Отображение информации из таблицы, django
(Извините за вопрос, но я новичок в django) Я ищу, чтобы показать информацию из моей базы данных 'профиль', но я не нашел, как это сделать... Есть две функциональности, которые должны отображаться на моем 'infos.html': одна часть для информации о пользователе, такой как почта и день рождения, вторая часть для избранных элементов, которые были добавлены пользователем.
#views.py -- post
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.db import models
from .models import Post
from django.utils import timezone
from django.contrib import messages
from django.contrib.auth import logout
from django.urls import reverse, reverse_lazy
from .forms import PostForm
from django.contrib.auth.decorators import login_required
import datetime
def index(request):
posts = Post.objects.order_by('-id')
posts_number = posts.count()
context = {
'posts' : posts,
'posts_number': posts_number,
}
return render(request, 'blog/pages/index.html', context)
def details(request, pk):
post = Post.objects.get(pk=pk)
context = {
'post': post,
}
return render(request, 'blog/pages/details.html', context)
@login_required
def new_post(request):
if request.method == 'POST':
form =PostForm(request.POST, request.FILES)
if form.is_valid():
form = form.save(commit=False)
form.author= request.user
form.save()
return redirect('new_post')
else:
form = PostForm()
context ={
'form' : form,
}
return render(request, 'blog/pages/new_post.html', context)
@login_required
def update_post(request,pk):
post = Post.objects.get(pk=pk)
if post.author == request.user :
if request.method == 'POST':
form = PostForm(request.POST, request.FILES, instance=post)
if form.is_valid():
form.save()
return redirect('index')
else:
form = PostForm(instance =post)
else :
raise Http404
context = {
'form' : form,
'post' : post,
}
return render(request,'blog/pages/update_post.html', context )
@login_required
def delete_post(request, pk):
if post.author == request.user :
post = Post.objects.get(pk=pk)
post.delete()
return redirect('index')
else :
raise Http404
return render(request, 'blog/pages/delete_post.html')
#models.py -- post
from django.conf import settings
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
#image = models.ImageField(upload_to='{posts_image/}',null = True, blank = True)
image= models.ImageField(null= True, blank = True)
favoris = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='favoris', blank=True,)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
#views.py -- account
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages
from .models import Profile
from blog.models import Post
from .forms import UserForm, ProfileForm, LoginForm
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
# Create your views here.
@login_required
def informations(request):
context = {
'informations': informations,
}
return render(request, 'accounts/infos.html', context)
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
profile_form= ProfileForm(request.POST)
if form.is_valid() and profile_form.is_valid():
user = form.save(commit=False)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.save()
return redirect('account:login')
else:
form = UserCreationForm()
profile_form = ProfileForm()
context = {
'form' : form ,
'profile': profile_form,
}
return render(request, 'accounts/register.html', context)
@login_required
def favourite_add(request,pk):
post = Post.objects.get(pk=pk)
if post.favoris.filter(pk=request.user.pk).exists():
post.favoris.remove(request.user)
else:
post.favoris.add(request.user)
context = {
'post':post,
}
return render(request,'accounts/infos.html',context)
@login_required
def favourite_list(request):
new = Post.filter(favoris = request.user)
context={
'new': new,
}
return render(request, 'account:infos.html', context)
#infos.html
{% extends 'blog/layouts/base.html' %}
{% load static %}
{% block title %} Home{% endblock title %}
{% block body%}
<h3>Vos informations: {{ user }} </h3>
<p></p>
<h3>Vos recette favorites : </h3>
<div class="row row-cols-md-3 row-cols-sm-2" >
{% for post in new %}
<div class="col">
<div class="card mb-3 ">
{% if post.image %}
<img src="{{ post.image.url }}" class="card-img-top img-thumbnail" alt="...">
{% endif %}
<div class="card-body">
<h5 class="card-title"> {{post.title|truncatechars:50}}</h5>
<p class="card-text"> {{ post.content }}</p>
</div>
<div class="card-footer">Créateur : {{ post.author}}</div>
</div>
</div>
{% endfor %}
</div>
{% endblock body %}