Django : How to show logged in users data from database - python

I am working on invoice management system having in which user can add invoice data and it will save in database and whenever user logged in the data will appear on home page.but the problem if whenever any user logged in the home page showing other users data also but i want active users data only. could you guys help me.
here is my home page,you can see i am logged in through user 1 but at home page user 2 data also appear
here is my code
views.py
from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import (
ListView,
DetailView,
CreateView,
UpdateView,
DeleteView
)
from .models import Invoicelist
def home(request):
context = {
'invoices': Invoicelist.objects.all()
}
return render(request, 'invoicedata/home.html', context)
class InvoiceListView(ListView):
model = Invoicelist
template_name = 'invoicedata/home.html' # <app>/<model>_<viewtype>.html
context_object_name = 'invoices'
class InvoiceDetailView(DetailView):
model = Invoicelist
class InvoiceCreateView(LoginRequiredMixin, CreateView):
model = Invoicelist
fields = ['issuer','invoice_number','date','amount','currency','other']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
class InvoiceUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Invoicelist
fields = ['issuer','invoice_number','date','amount','currency','other']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
invoice = self.get_object()
if self.request.user == invoice.author:
return True
return False
class InvoiceDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Invoicelist
success_url = '/'
def test_func(self):
invoice = self.get_object()
if self.request.user == invoice.author:
return True
return False
def about(request):
return render(request, 'invoicedata/about.html', {'title': 'About'})
models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from django.urls import reverse
class Invoicelist(models.Model):
issuer = models.CharField(max_length=50)
invoice_number = models.CharField(max_length=50)
date = models.CharField(max_length=50)
amount = models.IntegerField()
currency = models.CharField(max_length=10)
other = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return (self.issuer)
def get_absolute_url(self):
return reverse('invoice-detail', kwargs={'pk': self.pk})
home.html
{% extends "invoicedata/base.html" %}
{% block content %}
{% for invoice in invoices %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<h2><a class="article-title" href="{% url 'invoice-detail' invoice.id %}">{{ invoice.issuer }}</a></h2>
</div>
<p class="article-content">{{ invoice.invoice_number }}</p>
<p class="article-content">{{ invoice.date }}</p>
<p class="article-content">{{ invoice.amount }}</p>
<p class="article-content">{{ invoice.currency }}</p>
<p class="article-content">{{ invoice.other }}</p>
<div class="article-metadata">
<small class="text-muted">{{ invoice.author }}</small>
</div>
</div>
</article>
{% endfor %}
{% endblock content %}
invoicelist_deatil.html
{% extends "invoicedata/base.html" %}
{% block content %}
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="#">{{ object.author }}</a>
<small class="text-muted">{{ object.date }}</small>
{% if object.author == user %}
<div>
<a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'invoice-update' object.id %}">Update</a>
<a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'invoice-delete' object.id %}">Delete</a>
</div>
{% endif %}
</div>
<h2 class="article-issuer">{{ object.issuer }}</h2>
<p class="article-invoice_number">{{ object.invoice_number }}</p>
<p class="article-date">{{ object.date }}</p>
<p class="article-amount">{{ object.amount }}</p>
<p class="article-currency">{{ object.currency }}</p>
<p class="article-other">{{ object.other }}</p>
</div>
</article>
{% endblock content %}

You'll have to override get_queryset() on e.g. the list view to only include the desired user's invoices. (You'll want to do this on the update view too, to avoid users being able to edit each others' invoices.)
As an aside, your model should be called Invoice, unless a single instance of the model actually represents a list of invoices.
class InvoiceListView(ListView):
model = Invoicelist
template_name = 'invoicedata/home.html'
context_object_name = 'invoices'
def get_queryset(self):
return self.model.objects.all().filter(issuer=self.request.user)

Related

Django: How do I update my inventory in the database of only the boxes that are checked?

I am creating a web application that will serve as a grocery store. I want it to work in a way so that when customers click on the checkbox and click submit, then the database will subtract the inventory quantity by 1. I am having trouble being able to capture the information from the checkboxes and then using that to subtract 1 from the inventory.
models.py
class Post(models.Model):
title = models.CharField(max_length=100)
Price = models.DecimalField(max_digits=4, decimal_places=2,default=1)
Sale = models.DecimalField(max_digits=4, decimal_places=2,default=1)
quantity = models.IntegerField(default=1)
author = models.ForeignKey(User, on_delete=models.CASCADE)
category = TreeForeignKey('Category',null=True,blank=True, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
views.py
class PostListView(ListView):
model = Post
template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html
context_object_name = 'posts'
class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Post
fields = ['title', 'Price', 'Sale', 'quantity', 'category',]
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
Post = self.get_object()
#editor = self.get_object()
if self.request.user == Post.author:
return True
return False
home.html
{% extends "blog/base.html" %}
{% block content %}
{% for post in posts %}
{% if post.quantity > 0 %}
<input type="checkbox" name="product[]" id=" {{ post.id }} ">
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{
post.category }}</a>
</div>
<h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{
post.title }}</a></h2>
<p class="article-content"> Price: ${{ post.Price }}</p>
<p class="article-content"> Sale: ${{ post.Sale }}</p>
Inventory count: {{ post.quantity }}
</input>
</div>
</article>
{% else %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{
post.category }}</a>
</div>
<h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{
post.title }}</a></h2>
<p class="article-content"> Price: ${{ post.Price }}</p>
<p class="article-content"> Sale: ${{ post.Sale }}</p>
Inventory count: {{ post.quantity }}
<p>Out Of Stock!</p>
</div>
</article>
{% endif %}
{% endfor %}
<button type="submit" name="Purchase">Confirm Purchase</button>
{% endblock content %}
urls.py
path('', PostListView.as_view(), name='blog-home'),
I have attached a picture of what the home page looks like as a reference. Any help is appreciated. Thank you.
Include {{ post.id }} as value to checkboxes:
<input type="checkbox" name="products" id="product_{{ post.id }}" value="{{ post.id }}" />
Then get the selected checkboxes in the view:
request.POST.getlist('products')
Here you will be getting the list of id of selected products and you can use it to decrease the quantity.

How to add comments functionality to a django web app?

I want to add the functionality of adding comments in the same html page with post details starting from this class based view.
I also have left below the model and the html template that I want to use.
Please help me
The class based view that I want to use as a starting point :
class PostDetailView(DetailView):
model = Post
The model:
class Comments(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
content = models.TextField()
date_added = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.content
The html template:
<div id="comments">
<h3>{{ comments.total }}</h3>
<ol class="commentlist">
{% for comment in comments %}
<li class="depth-1">
<div class="avatar">
<img width="50" height="50" alt=""
src="{{ comment.user.profile.image.url }}"
class="avatar">
</div>
<div class="comment-content">
<div class="comment-info">
<cite>{{ comment.user }}</cite>
<div class="comment-meta">
<time datetime="2014-07-12T23:05"
class="comment-time">{{ comment.date_added|date:"F d, Y" }}</time>
</div>
</div>
<div class="comment-text">
<p>{{ comment.content }}</p>
</div>
</div>
</li>
{% endfor %}
</ol> <!-- /commentlist -->
<!-- respond -->
<div class="respond">
<h3>Leave a Comment</h3>
<!-- form -->
<form action="" method="POST">
{% csrf_token %}
<fieldset>
<div class="group">
{{ form|crispy }}
<button class="submit full-width" type="submit">Add Comment</button>
</div>
</fieldset>
</form> <!-- /contactForm -->
</div> <!-- /respond -->
</div> <!-- /comments -->
Override DetailView's get_context_data method to transfer comments through context. add this method in your class PostDetailView.
def get_context_data(self, **kwargs):
context = {}
if self.object:
context['object'] = self.object
context['comments']=Comments.objects.all() #modify this queryset according to how you want to display comments
context.update(kwargs)
return super().get_context_data(**context)
than in template you can include this piece of code
{% for comment in comments%}
<div>
{{comment}}
</div>
{% endfor %}
and to get comments, In forms.py
from django import forms
from .models import Comments
class CommentForm(forms.Form):
class Meta:
model = Comments
fields = [] #mention fields of comments u want to render in form
you have to extend FormView along with DetailView as DetailView dosent have post method to override.
So in views.py:
from .forms imoprt CommentForm
from django.views.generic.edit import FormView
class PostDetailView(DetailView, FormView):
model = Post
form_class = CommentForm
def post(self, request, *args, **kwargs):
form = self.get_form()
if form.is_valid():
#do what you want with data
I suggest you go through the Methods of the classes to override them.FormView

How to create a comment-creation page related to a single blog-style post in Django

I am trying to create a comment creation page related to a single post on a blog-style site using Django.
The home page has a list of posts, each with a "comment" button. Ideally this "comment" button would then take you to a page that would have the original post listed at the top with the comment creation form underneath it.
I've been trying to figure out a way to access the data I'm looking for using primary keys but am not sure how to tie everything together.
Here are the 2 models I am trying to access (Post and Comment):
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
title = models.CharField(max_length=128)
content = models.TextField()
image = models.ImageField(upload_to='post_pics', blank=True)
date_posted = models.DateTimeField(default=timezone.now)
def get_absolute_url(self):
return reverse('home')
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
user = models.ForeignKey(User, on_delete=models.CASCADE)
comment = models.TextField()
date_created = models.DateTimeField(default=timezone.now)
And the urls.py:
from django.urls import path
from .views import PostCreateView, PostListView, VehicleListView, CommentCreateView
from . import views
urlpatterns = [
path('', PostListView.as_view(), name='home'),
path('comment/new/<int:pk>', CommentCreateView.as_view(), name='comment-create'),
]
This is my current HTML for the home page (currently adds the post id to the end of the HTML on linked "comment-create" page):
{% for post in posts %}
<div class="infinite-item">
<div class="card m-3">
<div class="card-body" style="background-color:#bdcade; padding-bottom:0px">
<div class="media mb-3">
<img src="{{ user.profile.image.url }}" class="d-block ui-w-40 rounded-circle" style="width:40px;height:auto;" alt="">
<div class="media-body ml-3">
<h5 style="color:#ffffff">{{ post.user.username }}</h5>
<div class="small text-muted">Yesterday</div>
</div>
</div>
</div>
<div class="card-body">
<h5 class="card-title">{{ post.title }}</h5>
<p class="card-text">{{ post.content }}</p>
<div class="btn-group" role="group">
<button type="button" class="btn btn-secondary">Like</button>
<a class="btn btn-secondary" href="{% url 'comment-create' post.id %}" role="button">Comment</a>
</div>
</div>
</div>
</div>
This is my current HTML for the comment-creation page:
{% block content %}
<div class="card m-3">
<div class="card-body" style="background-color:#bdcade; padding-bottom:0px">
<div class="media mb-3">
<img src="{{ post.user.profile.image.url }}" class="d-block ui-w-40 rounded-circle" style="width:40px;height:auto;" alt="">
<div class="media-body ml-3">
<h5 style="color:#ffffff">{{ post.user.username }}</h5>
<div class="small text-muted">{{ post.title }}</div>
</div>
</div>
</div>
<div class="card-body">
<h5 class="card-title">{{ post.title }}</h5>
<p class="card-text">{{ post.content }}</p>
<div class="btn-group" role="group">
<button type="button" class="btn btn-secondary">Like</button>
<button type="button" class="btn btn-secondary">Comment</button>
</div>
</div>
</div>
<br>
<div class="container primary-segments">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Post Comment</button>
</div>
</form>
</div>
{% endblock content %}
Here is the view for comment creation page (using get_context_data to access the Post model):
class CommentCreateView(LoginRequiredMixin, CreateView):
model = Comment
template_name = 'home/comment-form.html'
fields = ['comment',]
def get_context_data(self, **kwargs):
context = super(CommentCreateView, self).get_context_data(**kwargs)
pk = self.kwargs['pk']
context['post'] = Post.objects.filter(id=pk)
return context
def form_valid(self, form):
form.instance.user = self.request.user
return super().form_valid(form)
Currently, I can't access any of the data for the post in the comment creation page. I think it has to do with how I'm trying to tie the pk to the post within the -get_context_data` function. The primary key for the desired post is showing up in the URL, just not sure how to get at the right data.
Any help would be much appreciated. Thank you!
So it looks to me like you're using pk wrong here.
The pk in this code segment here:
def get_context_data(self, **kwargs):
context = super(CommentCreateView, self).get_context_data(**kwargs)
pk = self.kwargs['pk']
is the pk of the comment, however you're trying to use it to lookup a Post with context['post'] = Post.objects.filter(id=pk). Remember that pk stands for primary key and references the object that you declared as the model for your view. If you want the Post associated with that Comment you'll need to search for it using Comment.post since that's the declared foreign key inside your model.
After a lot of Googling/trial-and-error, I found a solution that got me what I was looking for.
Updated my View from THIS (note: I was trying to force a specific PK to test if it would filter to the correct data, but for some reason I still couldn't access anything):
class CommentCreateView(LoginRequiredMixin, CreateView):
model = Comment
template_name = 'home/comment-form.html'
fields = ['comment',]
def get_context_data(self, **kwargs):
context = super(CommentCreateView, self).get_context_data(**kwargs)
pk = 7
context['post'] = Post.objects.filter(id=pk)
return context
def form_valid(self, form):
form.instance.user = self.request.user
return super().form_valid(form)
To THIS:
class CommentCreateView(LoginRequiredMixin, CreateView):
model = Comment
template_name = 'home/comment-form.html'
fields = ['comment',]
def get_context_data(self, **kwargs):
context = super(CommentCreateView, self).get_context_data(**kwargs)
context['post'] = Post.objects.get(pk=self.kwargs['pk'])
return context
def form_valid(self, form):
form.instance.user = self.request.user
return super().form_valid(form)
Have a basic, high-level understanding of what this is doing (grabbing the PK from the URL), but am not entirely sure why the original .filter() method wasn't working.
If anyone could provide some context as to what's going on behind the scenes here, I'd love to see it.
Thanks!

Not being able to display comments in template

I'm making a Post and Comment model by taking reference from internet. i created and Post and Comment model and it looks ok in django admin panel. i can add post and also a comment to any particular post. but getting trouble when I'm trying to display the comment under the post in templates(under post detail views). PLEASE HELP
models.py
class Post(models.Model):
author = models.ForeignKey(User,on_delete=models.CASCADE)
title = models.CharField(max_length=100)
content = RichTextField()
tags = models.CharField(max_length=50,blank=True,null=True)
date_posted = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail',kwargs={'pk':self.pk})
class Comment(models.Model):
post = models.ForeignKey(Post,on_delete=models.CASCADE)
author = models.ForeignKey(User,max_length=50,on_delete=models.CASCADE)
text = models.TextField()
create_date = models.DateTimeField(default=timezone.now)
def get_absolute_url(self):
return reverse('discuss')
views.py
class PostDetailView(DetailView):
model = Post
def add_comment_to_post(request,pk):
return get_object_or_404(Post,pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post= post
comment.save()
return redirect('post-detail',pk=post.pk)
else:
form = CommentForm()
return render(request, 'discuss/comment_form.html',{'form':form})
def comment_remove(request,pk):
comment = get_object_or_404(Comment,pk=pk)
post_pk = comment.post.pk
comment.delete()
return redirect('post-detail', pk=post_pk)
post_detail.html
{% extends 'index.html' %}
{% block content %}
<article class="media content-section">
<div class="medaia-body">
<img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}" alt="image not found">
<div class="article-metedata">
<a class="mr-2" href="{% url 'user-posts' object.author.username %}">{{object.author}}</a>
<small class="text-muted">{{ object.date_posted|date:"F d, Y"}}</small>
</div>
<h2 class="article-title">{{ object.title }}</h2>
<img class="query-img" src="{{ object.image.url }}" alt="image not found">
<p class="article-content">{{ object.content|safe }}</p>
</div>
</article>
{% if object.author == user %}
<div class="post-update-delete">
<button class="btn btn-outline-primary">Edit Post</button>
<button class="btn btn-outline-primary">Delete Post</button>
</div>
{% endif %}
<hr>
<a class="btn btn-primary btn-comment" href="{% url 'add_comment_to_post' pk=post.pk %}">Add Comment</a>
<!-- ############################### ABOVE CODE IS WORKING ############################# -->
<!-- ########################## GETTING PROBLEM IN BELLOW CODE ######################### -->
{% for comment in object.comments.all %}
{% if user.is_authenticated %}
{{ comment.create_date }}
{{ comment.text|safe|linebreaks }}
{{ comment.author }}
{% endif %}
{% empty %}
<p>No Comment</p>
{% endfor %}
{% endblock %}
in post_deatil.html i also tried {% for comment in post.comments.all %} but it is also not working
Since you did not specify a related_name=… parameter [Django-doc], the related_name is by default comment_set, so you iterate over the comments with:
{% for comment in object.comment_set.all %}
…
{% endfor %}
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

How to integrate a function based view into a class based view in Django?

In my site I have 2 sections for users. The user posts page and the profile page. The profile page has all their info on it, so username, description, first/last name, etc. And the user posts page has all their posts on it. However, I want to integrate them together somehow.
Here is some of the code.
Here is the view for the User Posts
class UserPostListView(ListView):
model = Post
template_name = 'mainapp/user_posts.html'
context_object_name = 'posts'
def get_queryset(self):
user = get_object_or_404(User,username=self.kwargs.get('username'))
return Post.objects.filter(author=user).order_by('-published_date')
As you can see, I am returning the specific users posts.
And now here is my profile view
def view_profile(request,pk=None):
if pk:
user_profile = User.objects.get(pk=pk)
else:
user_profile = request.user
context = {'user':user_profile}
return render(request,'mainapp/profile.html',context)
It returns all the user's info.
Here is the HTML code for both the profile and user posts page
{% block content %}
<div class="profile-page-container">
<div class="profile-page-info">
<div class="profile-page-banner">
<div class="profile-page-banner-background">
<!-- <img src="https://cdn.pixabay.com/photo/2017/08/30/01/05/milky-way-2695569_960_720.jpg" alt="{{ user }}'s Background Image" > -->
</div>
<div class="profile-page-banner-text">
<h2 title="{{ user }}" id="username-profile-page">{{ user|safe|linebreaksbr|truncatechars_html:25 }} {% if user.userprofileinfo.verified %} <span class="image-profile-verified"><img draggable="false" title="Verified User" class="verifed" src="{% static 'images\verified.png' %}" alt="verified" width="25" height="25" srcset=""></span> {% endif %}</h2>
<p>{{ user.first_name }} {{ user.last_name }}</p><br>
</div>
</div>
<div class="profile-page-user-desc-box">
<p>{{ user.userprofileinfo.description }}</p>
<p>{{ user.userprofileinfo.website }}</p>
<p>{{ user.userprofileinfo.joined_date |date:"F d Y" }}</p>
</div>
<br>
{% if user.userprofileinfo.image %}
<img class="rounded-circle account-img" src="{{ user.userprofileinfo.image.url }}" alt="{{ user }}'s Profile Picture'">
{% endif %}
</div>
<div class="user-post-user-profile-page">
<h1 title="{{ user }}">Posts</h1>
{% for post in posts %}
<div class="content">
<div class="post">
<h1 class='posttitle'>{{ post.title }}</h1>
<img class="user-image" src="{{ post.author.userprofileinfo.image.url }}" alt="pfp" width="20%" height="20%">
{% if post.published_date %}
<!-- <div class="postdate">
<i class="fas fa-calendar-day"></i> <p>Posted {{ post.published_date|timesince }} ago</p>
</div> -->
<div class="posted-by">
<p>Posted by <strong>{{ post.author }}</strong> {{ post.published_date|timesince }} ago</p>
</div>
{% else %}
<a class="pub-post" href="{% url 'mainapp:post_publish' pk=post.pk %}">Publish</a>
{% endif %}
<p class='postcontent' >{{ post.text|safe|linebreaksbr }}</p>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
And here is the user_posts page
{% block content %}
<div class="sidebar">
<p class="active" href="#">{{ view.kwargs.username }}</p>
<button class="commentbtn"><a class="aclass" href="#">Connect with {{ view.kwargs.username }}</a></button>
<p>{{ user.userprofileinfo.email }}</p>
<p>Lorem</p>
</div>
{% for post in posts %}
<div class="content">
<div class="post">
<h1 class='posttitle'>{{ post.title }}</h1>
<img class="user-image" src="{{ post.author.userprofileinfo.image.url }}" alt="pfp" width="20%" height="20%">
{% if post.published_date %}
<!-- <div class="postdate">
<i class="fas fa-calendar-day"></i> <p>Posted {{ post.published_date|timesince }} ago</p>
</div> -->
<div class="posted-by">
<p>Posted by <strong>{{ post.author }}</strong> {{ post.published_date|timesince }} ago</p>
</div>
{% else %}
<a class="pub-post" href="{% url 'mainapp:post_publish' pk=post.pk %}">Publish</a>
{% endif %}
<p class='postcontent' >{{ post.text|safe|linebreaksbr }}</p>
</div>
</div>
{% endfor %}
{% endblock %}
I have tried to merge the FBV into the CBV by cutting it and pasting it below the get_queryset method So like this
def get_queryset(self):
#... code here
def view_profile(request,pk=None):
#... code here
However this did not work. I am just curious as to how I can integrate both together so I can have the best of both worlds in one place
EDIT: Here are the models
class UserProfileInfo(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,max_length=30)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
description = models.CharField(max_length=150)
website = models.URLField(max_length=200)
image = ProcessedImageField(upload_to='profile_pics',
processors=[ResizeToFill(150, 150)],
default='default.jpg',
format='JPEG',
options={'quality': 60})
joined_date = models.DateTimeField(blank=True,null=True,default=timezone.now)
verified = models.BooleanField(default=False)
def __str__(self):
return f'{self.user.username} Profile'
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
and now the post
class Post(models.Model):
author = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE)
title = models.CharField(max_length=75)
text = models.TextField()
group = models.ForeignKey(Group,null=True,blank=True,related_name='posts',on_delete=models.CASCADE)
created_date = models.DateTimeField(default=timezone.now)
image = models.ImageField(upload_to='post_images',blank=True,null=True)
file = models.FileField(upload_to='post_files',blank=True,null=True)
published_date = models.DateTimeField(blank=True,null=True,auto_now_add=True)
comments_disabled = models.BooleanField(default=False)
NSFW = models.BooleanField(default=False)
spoiler = models.BooleanField(default=False)
tags = TaggableManager()
def __str__(self):
return self.title
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
Also in continuation to Ian answer, if you have a direct relationship between models then you can simply get the posts for the particular user like this:
def view_profile(request,pk=None):
if pk:
user_profile = User.objects.get(pk=pk)
user_posts = Posts.objects.filter(user__id=pk) #<---add these
else:
user_profile = request.user
user_posts = Posts.objects.filter(user__id = request.user.id) #<---add these
context = {
'user':user_profile,
'user_posts':user_posts
}
return render(request,'mainapp/profile.html',context)
A simple class based view for getting a user:
class UserDetailView(DetailView):
model = User
template_name = 'mainapp/profile.html'
context_object_name = 'user'
Relationships (foreign keys) can be followed backwards. Every foreign key has a reverse relationship defined (unless you set reverse_name to +...) it will usually be named <modelname>_set on the model referenced by the foreign key
For example, the following two lines are equivalent
Post.objects.filter(author=user)
user.post_set.all()
This can be used in your profile template
{% for post in user.post_set.all %}
...
{% endfor %}

Categories

Resources