How to create a video blog with Django? - python

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 %}

Related

How to output Django form on the browser

I'm learning to create a post and comment session with Django and I'm following a tutorial but I don't know why I'm not getting the same result as the one in the tutorial. The post aspect is working but the form for comments is not being displayed on the browser. Even after going through Django documentation and other resources online, I still don't see where I'm getting it wrong. I have the following directories and files:
start is my app directory while education is the main django directory
start/models.py
class Comment (models.Model):
post = models.ForeignKey(Post,related_name = 'comments', on_delete = models.CASCADE)
name = models.CharField()
email = models.Email()
body = models.TextField()
createdAt = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['createdAt']
start/forms.py
from django import forms
from .models import Comment
class post_comment(forms.ModelForm):
class Meta:
model = Comment
fields = ['name', 'email', 'body']
start/views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .forms import post_comment
def fullPost(request, slug):
post = Post.object.all()
return render (request, 'start/start.html', {'post': post})
if request.method == 'POST':
form = post_comment(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect ('fullPost', slug=post.slug)
else:
form = post_comment()
return render (request, 'start/fullPage.html', {'post': post, 'form': form})
start/templates/start/fullpost.html
•••
<h3>Comment</h3>
<form method = 'post' action = '.'>
{% csrf_token %}
{{ form.as_p }}
<button> Post comment </button>
</form>
The issue is with the structure of the fullpost view
In this line:
return render (request, 'start/start.html', {'post': post})
the function is exited without the form.
You could try:
start/views.py
...
def fullPost(request, slug):
post = Post.object.all()
#return render (request, 'start/start.html', {'post': post})
if request.method == 'POST':
form = post_comment(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect ('fullPost', slug=post.slug)
else:
form = post_comment()
return render (request, 'start/fullPage.html', {'post': post, 'form': form})
...
If form.is_valid() fails, it will fall through to the end, rendering the form with the incorrect data.
Edit
Since you are learning , the following line may be wrong
post = Post.object.all()
because objects.all() retrieves all the posts in the db. Unless you want to comment all posts, you may need to rewrite it as follows:
post=Post.objects.get(slug=slug)
This will retrieve the post with the matching slug, assuming the slug field is unique.
https://docs.djangoproject.com/en/3.1/topics/db/queries/#retrieving-all-objects
https://docs.djangoproject.com/en/3.1/topics/db/queries/#retrieving-a-single-object-with-get

"Post.user" must be a "User" instance

I am new to using django and I'm creating a simple webpage that takes in user input and saves it to the Model Form
models.py:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Post(models.Model):
post = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE)
forms.py
from django import forms
from .models import Post
class HomeForm(forms.ModelForm):
post = forms.CharField()
class Meta:
model = Post
fields = ('post',)
views.py
from django.shortcuts import render, redirect
# Create your views here.
from django.http import HttpResponse
from django.views.generic import TemplateView
from .forms import HomeForm
class HomeView(TemplateView):
template_name = 'home.html'
def get(self, request):
form = HomeForm()
return render(request, self.template_name, {'form': form})
def post(self, request):
form = HomeForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.user = request.user
post.save()
text = form.cleaned_data['post']
form = HomeForm()
return redirect('home.html')
args = {'form': form, 'text': text}
return render(request, self.template_name, args)
home.html
{% block body %}
<div class ='container'>
<h1>Home</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type ='submit'>Submit</button>
</form>
</div>
{% endblock %}
When I run the server the webpage comes up normal but when I type in some input an error page pops up and says : ValueError at /
Cannot assign ">": "Post.user" must be a "User" instance.
Any Help would be appreciated!

Can't get forms to render in Django

I'm working on a project and I don't get the django forms to render on any of my pages. I've compared it to django girls code, as that is what I usually consult but it looks virtually identical to it. It's not just this page, my other pages have issues with rendering the forms as well. Here's the code:
Views.py
from django.shortcuts import render
from .models import *
from .forms import *
from django.shortcuts import render, get_object_or_404
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.db.models import Sum
from django.utils import timezone
from django.views.decorators.http import require_POST
from .cart import Cart
from django.db import transaction
from django.contrib import messages
#login_required
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.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm(instance=Post)
return render(request, 'rentadevapp/post_edit.html', {'rentadevapp': post_edit}, {'form': form})
Forms.py
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'text',)
post_edit.html
{% extends 'rentadevapp/base.html' %}
{% load staticfiles %}
{% load crispy_forms_tags %}
{% block content %}
<head>
<link rel="stylesheet" href="{% static 'css/post_edit.css' %}">
</head>
<body>
<div class="container"><br>
<h2>New Post</h2><br>
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
</div>
</body>
{% endblock %}
Models.py
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)
updated_date = models.DateTimeField(auto_now_add=True)
price = models.DecimalField(max_digits=10, decimal_places=2, default='0')
class Meta:
ordering = ('title',)
def created(self):
self.created_date = timezone.now()
self.save()
def updated(self):
self.updated_date = timezone.now()
self.save()
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
I'm pretty stuck and have spent a couple hours trying to figure this out. Any help is really appreciated.
Thanks!
Your form isn't returned to the template in the context.
In Django 1.11 or 2.2 the render function call in your view should return a dictionary of context variables as the third argument, but you've got two dictionaries. The 4th argument where you've got a dictionary containing the form is being passed as content_type which is then used in the HttpResponse so I'm quite surprised there isn't something strange happening or an error seen.
So you're doing;
return render(request, 'rentadevapp/post_edit.html', {'rentadevapp': post_edit}, {'form': form})
What you need to do is;
context = {'form': form, 'rentadevapp': post_edit}
return render(request, 'rentadevapp/post_edit.html', context)
Prior to 1.10 render had a different signature, but the first three arguments of request, template_name, context have been that way since <1.8

(HELP) Django Model Form does not recognize Image file

I created a Form using one of my models i.e (Post), for my blog website. The form is meant for writers to post articles. In that form there is an Image attribute where the writer can upload an image. However, when i try to upload an image and post it, i get a feedback saying "field required", i think the form is not recognizing the image am trying to upload onto the the database. please help:
this is the form view from views.py:
def formview(request):
form = PostForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
return render(request, 'form.html', {'form':form})
this is from forms.py:
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
image = forms.FileField
class Meta:
model = Post
fields = ['category', 'title', 'body', 'image', 'author']
this from my models.py:
class Post(models.Model):
category = models.ForeignKey(Category)
title = models.CharField(max_length=100)
pub_date = models.DateTimeField(auto_now_add=True)
body = models.TextField()
image = models.FileField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
likes = models.IntegerField(default=1)
def __str__(self):
return self.title
this is my forms.html template:
<form method="POST" action="">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Post</button>
this is my urls.py:
from django.conf.urls import url
from . import views
app_name = 'posts'
urlpatterns = [
url(r'^$', views.homeview, name='homeview'),
url(r'^(?P<pk>[0-9]+)$', views.postview, name='postview'),
url(r'^category/(?P<pk>[a-zA-Z0-9]+)/$', views.categoryview,
name='categoryview'),
url(r'^author/(?P<pk>[a-zA-Z0-9]+)/$', views.authorview, name='authorview'),
url(r'^add_post/$', views.formview, name='formview'),
]
these are the pics might help explain what am trying to say:
Filling the form and selecting the picture
Error message after trying to post
Thank you
def formview(request):
if request.method == 'POST':
form = PostForm(request.POST,request.FILES)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
else:
form = PostForm()
return render(request, 'form.html', {'form':form})
this form = PostForm(request.POST,request.FILES),you need add FILES to PostForm

Django Many-to-Many Accessing both Models

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})

Categories