I'm looking to build a small 'Twitter style' site using Django to get to grips with things and have decided to try and allow multiple users edit each post (eventually based on permissions). Now what I'm struggling with is accessing each user's posts. Below is the code for my model, view and template which shows "There aint no post here" for all users. I'm looking to be able to show all posts that the user has and don't seem to be getting anywhere:
models.py
from django.db import models
class User(models.Model):
username = models.CharField(max_length = 200)
email = models.EmailField(max_length = 75)
password = models.CharField(max_length = 64)
created_date = models.DateTimeField('date created')
def __unicode__(self):
return self.username
class Meta:
ordering = ('created_date',)
class Post(models.Model):
users = models.ManyToManyField(User)
title = models.CharField(max_length = 300)
post = models.TextField()
posted_date = models.DateTimeField('date created')
votes = models.IntegerField()
def __unicode__(self):
return self.title
class Meta:
ordering = ('posted_date',)
views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from users.models import User, Post
def index(request):
latest_user_list = User.objects.order_by('username')[:5]
context = {'latest_user_list': latest_user_list}
return render(request, 'users/index.html', context)
def detail(request, user_id):
user = get_object_or_404(User, pk=user_id)
post_list = Post.objects.filter(id == user.id)
return render(request, 'users/detail.html', {'user': user, 'post': post_list})
urls.py
from django.conf.urls import patterns, url
from users import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^(?P<user_id>\d+)/$', views.detail, name='detail'),
)
(template) - detail.html
<h1>{{ user.username }}</h1>
{% if post_list %}
<ul>
{% for post in post_list%}
<li>{{ post.title }}</li>
{% endfor %}
</ul>
{% else %}
<p> There aint no posts here </p>
{% endif %}
The variable you're passing to the template is called post not post_list.
Change the name for the list object in your view.
def detail(request, user_id):
user = get_object_or_404(User, pk=user_id)
post_list = Post.objects.filter(id == user.id)
return render(request, 'users/detail.html', {'user': user, 'post_list': post_list})
Related
I am learning Django. I have started with Django girls blog tutorial which is very basic. Now I want to convert this with the conceptual video blog where user can upload a video like Youtube and user will be able to play that video on the page blog. Besides, I want every post will be moderated by admin. Can anyone expert help me with some coding suggestion as I am newcomer? I have included the completed code bellow.
#ALL MODELS
from django.conf import settings
from django.db import models
from django.utils import timezone
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)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
###############################################################
# ALL VIEWS
from django.shortcuts import render, get_object_or_404, redirect
from .models import Post
from django.utils import timezone
from .forms import PostForm
def post_list(request):
posts = Post.objects.filter(
published_date__lte=timezone.now(
)).order_by('-published_date')
return render(request, 'blog/post_list.html', {'posts': posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
def post_new(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
# post.published_date = timezone.now()
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm()
return render(request, 'blog/post_edit.html', {'form': form})
def post_edit(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = PostForm(request.POST, instance=post)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
# post.published_date = timezone.now()
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm(instance=post)
return render(request, 'blog/post_edit.html', {'form': form})
###################################################################
# URL patterns
from django.urls import path
from . import views
urlpatterns = [
path('', views.post_list, name='post_list'),
path('post/<int:pk>/', views.post_detail, name='post_detail'),
path('post/new/', views.post_new, name='post_new'),
path('post/<int:pk>/edit/', views.post_edit, name='post_edit'),
]
#################################################################
# Forms
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'text',)
Guys I have solved my problem on my own. I have added just a simple code inside the video tag of html5. I have provided the code bellow.
Code for model:
from django.db import models
class VideoUploader(models.Model):
title = models.CharField(max_length = 100)
clip = models.FileField(upload_to='videos/%Y/%m/%d/')
description = models.TextField()
def __str__(self):
return self.title
HTML5 post list page:
{% block content %}
<div class="post">
<h2>{{ post.title }}</h2>
<video src="{{ post.clip.url }}" controls controlsList="nodownload"
width="640" height="480"></video>
<p>{{ post.description }}</p>
</div>
{% endblock %}
Pretty straight forward question….
My view named create_view renders data correctly out of my model and my other view named create_view_two view doesn’t.
How do I get my view named create_view_two to render data to home.html?
Cheers
user_profile/views.py
from django.http import HttpResponse, HttpResponseRedirect
from django.http import HttpResponseNotFound
from django.shortcuts import get_object_or_404
from django.shortcuts import render, redirect
from django.conf import settings
from .forms import HomeForm
from .models import Listing
from users.models import CustomUser
def create_view(request):
form = HomeForm(request.POST or None, request.FILES or None,)
user_profile = Listing.objects.all()
user = request.user
if request.method == "POST":
if form.is_valid():
listing_instance = form.save(commit=False)
listing_instance.user = user
listing_instance.save()
return redirect("myaccount")
context = {
'form': form, 'user_profile': user_profile
}
return render(request, "myaccount.html", context)
def create_view_two(request):
form_two = HomeForm(request.POST or None, request.FILES or None,)
user_profile_two = Listing.objects.all()
user = request.user
context = {
'form': form_two, 'user_profile': user_profile_two
}
return render(request, "home.html", context)
user_profile/models
from django.contrib import auth
from django.db import models
from django.urls import reverse
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.conf import settings
from users.models import CustomUser
class Listing (models.Model):
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True, null=True)
updated = models.DateTimeField(auto_now=True)
rank = models.CharField(max_length=100, null=True)
name = models.CharField(max_length=100)
address = models.CharField(max_length=100)
zip_code = models.CharField(max_length=100)
mobile_number = models.CharField(max_length=100)
cc_type = models.CharField(max_length=100, null=True)
cc_number = models.CharField(max_length=100, null=True)
cc_expiration = models.CharField(max_length=100, null=True)
cc_cvv = models.CharField(max_length=100, null=True)
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = Listing.objects.create(user=kwargs['instance'])
post_save.connect(create_profile, sender=CustomUser)
user_profile/urls.py
from django.conf.urls import url
from . import views
from django.urls import path, include
from django.conf import settings
from .views import create_view, create_view_two
urlpatterns = [
path('myaccount/', create_view, name='myaccount'),
path('home/', create_view_two, name='home'),
]
home.html
{% for profile_two in user_profile_two %}
{{ user_profile_two }}
{% endfor %}
myaccount.html
{% for profile in user_profile %}
<div class="user-info-heading payments-detail">
<p>Card Number:</p><span>{{ profile.cc_type }}</span>
<p>Card Type:</p><span>{{ profile.cc_number }}</span>
<p>Expiration Date:</p><span>{{ profile.cc_expiration }}</span>
<p>CVV:</p><span>{{ profile.cc_cvv }}</span>
</div>
{% endfor %}
In your home.html you should have:
{% for profile_two in user_profile %}
instead of:
{% for profile_two in user_profile_two %}
Given user_profile is the name you're giving it in the context dict.
UPDATE
If your code is exactly as you updated it, then your home.html should be like this:
{% for profile_two in user_profile %}
{{ profile_two }}
{% endfor %}
I'm creating a simple blog application. A user is logged in this application while He/She can comment any post on my blog application. But cant impletement that idea.
This is my models.py file
from django.db import models
# Create your models here.
from user.models import CustomUser
from django.conf import settings
from django.db import models
from django.urls import reverse
class BlogPost(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
blog_title=models.CharField(max_length=200)
blog_description=models.TextField()
blog_pub=models.DateTimeField(auto_now_add=True)
blog_update=models.DateTimeField(auto_now=True)
def __str__(self):
return self.blog_title
def get_absolute_url(self):
return reverse('blog:blog_post', kwargs={'pk': self.pk})
class Comment(models.Model):
blogpost=models.ForeignKey(BlogPost, on_delete=models.CASCADE)
comment=models.CharField(max_length=300)
author=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,blank=True, null=True)
author_name = models.CharField(max_length=50, default='anonymous', verbose_name=("user name"))
comment_pub = models.DateTimeField(auto_now_add=True)
comment_update = models.DateTimeField(auto_now=True)
def get_absolute_url(self):
return reverse('blog:home', kwargs={'pk':self.pk})
def __str__(self):
return self.comment
This is views.py file
class BlogPostSingle(DetailView, FormView):
model=BlogPost
template_name='blog/blog_post_single.html'
#fields = ['blog_title']
form_class = CreateCommentForm
success_url = '/blog/'
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
this is my forms.py file
class CreateCommentForm(ModelForm):
class Meta:
model=Comment
fields = ('comment', 'blogpost')
and this is my html file and forms section
{% if user.is_authenticated %}
<h5>Hi, {{user.name}} leave your comment now</h5>
<form action="" method="post">
{% csrf_token %} {{form.as_p}}
<input type="submit" value="Submit comment">
</form>
{% else %}
<p>You're not logged in this site, please log in for comment </p>
{% endif %}
My target Idea: Just user logged on my blog application. He can be able to comment any post on my blog application. And my Comment Models contain two forignkey field.
You should pass the user to your view's context, so it will be available in the template:
class BlogPostSingle(DetailView, FormView):
...
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['user'] = self.request.user
return context
on get_context_data see https://docs.djangoproject.com/en/2.0/ref/class-based-views/generic-display/#detailview
on self.request see
https://docs.djangoproject.com/en/2.0/topics/class-based-views/generic-display/#dynamic-filtering
I'm writing a small chat programm in Django but have problems getting any further.
Here's the code:
models.py
from django.db import models
from datetime import datetime
from django.utils import timezone
class Chat(models.Model):
chatname = models.CharField(max_length=100)
description = models.TextField()
created_at = models.DateTimeField(default=datetime.now, blank=True)
def __str__(self):
return self.chatname
class Comment(models.Model):
chat = models.ForeignKey(Chat, on_delete=models.CASCADE)
commenter = models.CharField(max_length=30)
comment = models.TextField()
created_at = models.DateTimeField(default=datetime.now, blank=True)
def __str__(self):
return self.comment
urls.py
from django.conf.urls import url
from . import views
from django.views.generic import ListView
from chat.views import CommentList
app_name = 'chats'
urlpatterns = [
url(r'^$', views.index, name="index"),
url(r'^comments/(?P<pk>[0-9]+)/$', views.CommentList.as_view(), name='comments'),
]
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth import authenticate, login
from django.views import generic
from .models import Chat, Comment
def index(request):
username = None
if request.user.is_authenticated():
username = request.user.username
chats = Chat.objects.all()[:10]
context = {
'chats':chats
}
return render(request, 'chat/index.html', context)
class CommentList(generic.ListView):
queryset = Comment.objects.filter(chat_id=1)
context_object_name = 'comments'
My comment_list.html
{% extends "chat/base.html" %}
{% block content %}
Go back
<h3>Comments</h3>
<h2>{{chat.id}}</h2>
<ul>
{% for comment in comments %}
<li>{{ comment.commenter }}: {{ comment.comment }}</li>
{% endfor %}
</ul>
{% endblock %}
My database structure contains these two models: Chat and Comment. Each chat(room) is supposed to have its own comments. I used 'models.ForeignKey' to be able to filter the comments for each chat(room). In my index.html I list all the chats and each of these has a hyperlink to the /comments/ section.
In my views.py I have this line: 'queryset = Comment.objects.filter(chat_id=1)'
Chat_id is the column in the comments sql table and as it is now it will only show comments that belong to the chat with pk=1. How can I auto access the chat for the different urls /comments/1/ /comments/2/ and so on..?
Hope the explanation is clear. Sorry beginner here, I can try to explain further if it doesn't make a lot of sense.
Best,
Fabian
You should define the get_queryset method instead of the standalone queryset attribute.
def get_queryset(self, *args, **kwargs):
return Comment.objects.filter(chat_id=self.kwargs['pk'])
Instead of CommentList you can use plain view:
def comments_index(request, chatid):
return render(request, 'xxx/comment_list.html', {
'comments': Comment.objects.filter(chat_id=chatid)
})
And in urls:
url(r'^comments/(?P<chatid>[0-9]+)/$', views.comments_index, name='comments'),
Im doing my first Django site myself after going through several tutorials and running into some errors that I can't figure out what the problem is as they are simple page requests.
I was trying to make a category detail view e.g. 127.0.0.1:8000/news and Ive followed the same setup as other pages such as the index and post detail which have worked fine but this is giving a 404.
here are my files
models.py
from django.db import models
from django.core.urlresolvers import reverse
class EntryQuerySet(models.QuerySet):
def published(self):
return self.filter(publish=True)
class Blog(models.Model):
title = models.CharField(max_length = 200)
slug = models.SlugField(max_length = 100, db_index = True)
body = models.TextField()
publish = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
category = models.ForeignKey('blog.category')
objects = EntryQuerySet.as_manager()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post_detail', kwargs={'slug':self.slug})
class Meta:
verbose_name = 'Blog entry'
verbose_name_plural = 'Blog entries'
ordering = ['-created']
class Category(models.Model):
cat_title = models.CharField(max_length = 200, db_index = True)
cat_slug = models.SlugField(max_length = 100, db_index = True)
def __str__(self):
return self.cat_title
def get_absolute_url(self):
return reverse('category_detail', kwargs={'cat_slug':self.cat_slug})
class Meta:
verbose_name = 'Category'
verbose_name_plural = 'Categories'
views.py
from django.views import generic
from . import models
class index_view(generic.ListView):
queryset = models.Blog.objects.published()
template_name = 'index.html'
class post_view(generic.DetailView):
model = models.Blog
template_name = 'post_view.html'
class category_view(generic.ListView):
model = models.Category
template_name = 'category_view.html'
class category_detail_view(generic.DetailView):
model = models.Category
template_name = 'category_detail_view.html'
class About_page(generic.DetailView):
template_name = 'about.html'
app urls.py
from django.conf.urls import url
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^$', views.index_view.as_view(), name='index'),
url(r'^categories/$', views.category_view.as_view(), name='category_detail'),
url(r'^(?P<slug>\S+)$', views.post_view.as_view(), name='post_detail'),
url(r'^(?P<cat_slug>\S+)$', views.category_detail_view.as_view(), name='category_detail_view'),
url(r'^about/$', views.About_page.as_view(), name='about'),
this is the category detail page 'category_detail_view.html'
{% extends 'base.html' %}
{% block title %} The category detail view page {% endblock %}
{% block category_detail %}
{% for cat_title in object_list %}
<ul>
<li>{{ category.cat_title }}</li>
{% endfor %}
</ul>
{% endblock %}
and the about page
{% extends 'base.html' %}
<h2>This is the about page</h2>
both of these pages return this error message
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/about/
Raised by: blog.views.post_view
No Blog entry found matching the query
I dont understand why 'blog.post_view' is being raised when neither of these templates refer to the post_view.
I have an index page with all published posts listed, a categories page with all categories listed and a post detail page all of which work fine and are almost exactly the same as these views and templates.
When Django resolves the url /about/, it goes through your url patterns in order. It matches the post_detail url pattern, so runs the post_view, treating about as a slug. Since you don't have any posts with the slug about, you get the 404 error.
One solution is to move the about url pattern above the post_detail pattern. You should also change the category url pattern, otherwise it won't work. For example, you could do:
url(r'^about/$', views.About_page.as_view(), name='about'),
url(r'^(?P<slug>\S+)$', views.post_view.as_view(), name='post_detail'),
url(r'^categories/(?P<cat_slug>\S+)$', views.category_detail_view.as_view(), name='category_detail_view'),