How to upload and display videos on django - django

I have been trying to add a view that uploades videos and displays them in the main template, well while adding code, I realized that the view that uploades the file isn't being rendered while the view that shows the uploded file in the template gets rendered but it doesnt show anything because nothing is being uploded. I dont know where the error might be but I think it is on the views.py, maybe the urls.py.
views.py
def upload(request):
if request.method == 'POST':
form = PostForm(request.POST, request.FILES)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
return redirect('home')
print('succesfully uploded')
else:
form = PostForm()
print('didnt upload')
return render(request, 'home.html', {'form': form})
def home(request):
contents = Post.objects.all()
context = {
"contents": contents,
}
print("nice")
return render(request, 'home.html', context)
urls.py
urlpatterns = [
path('', views.home, name='home'),
path('upload', views.upload, name='upload'),
]
models.py
class Post(models.Model):
text = models.CharField(max_length=200)
video = models.FileField(upload_to='clips', null=True, blank="True")
user = models.ForeignKey(User, related_name='imageuser', on_delete=models.CASCADE, default='username')
def __str__(self):
return str(self.text)
forms.py
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('text', 'video')
exclude = ['user']
home.html (uplodes the content and displays it)
<div class="user-content">
{% for content in contents %}
<li class="">{{ content.text }}
{% if content.video %}
<video class="video" width='400'>
<source src='{{ content.video.url }}' type='video/mp4'>
</video>
{% endif %}
</li>
{% endfor %}
</div>
<div class="uplodes">
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" name="text" placeholder="Add a comment..." required="" id="id_text">
<input type="file" name="video" id="id_video">
<button class="submit-button" type="submit">Save</button>
</form>
</div>

Related

Number of Likes is not increasing in the template but it's works in admin

I follow a tutorial in youtube just to add a like button to my Blog application, but the number of likes is not increasing in the template. but its increase when I highlight a user and hit save in the admin area. I mean its working fine in the admin but not in template.
How can I set that ?
the model:
class Photo(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
category = models.CharField(max_length=30,null=True, blank=False)
image = models.ImageField(null=False, blank=False)
description = models.TextField(null=True)
date_added = models.DateTimeField(auto_now_add=True)
likes = models.ManyToManyField(User, related_name='blog_posts')
def total_likes(self):
return self.likes.count()
def __str__(self):
return str(self.category)
the view:
def like(request, pk):
post = get_object_or_404(Photo, id=request.GET.get('post_id'))
post.Likes.add(request.user)
return HttpResponseRedirect(reverse('view', args=[str(pk)]))
def viewPhoto(request, pk):
post = get_object_or_404(Photo, id=pk)
photo = Photo.objects.get(id=pk)
stuff = get_object_or_404(Photo, id=pk)
total_likes = stuff.total_likes()
return render(request, 'photo.html', {'photo': photo, 'post': post, 'total_likes':
total_likes})
the templates:
<form action="{% url 'Photo' photo.id %}" method="POST">
{% csrf_token %}
{{ total_likes }}
<button type="submit", name="post_id" value="{{ post.id }}">Touch</button>
</form>
the urls:
path('', views.login, name='login'),
path('home', views.home, name='home'),
path('view/<str:pk>/', views.viewPhoto, name='Photo'),
path('post/create', views.PostCreativeView.as_view(), name='post_create'),
path('register', views.register, name='register'),
path('comment/<str:pk>/', views.comment, name='comment'),
path('like/<str:pk>/', views.like, name='like_post'),
Well it's very simple to get the number of liked objects in your form by simple doing something like this :
# In your view add s to the post variable
def viewPhoto(request, pk):
posts = get_object_or_404(Photo, id=pk)
photo = Photo.objects.get(id=pk)
stuff = get_object_or_404(Photo, id=pk)
total_likes = stuff.total_likes()
return render(request, 'photo.html', {'photo': photo, 'posts': posts, 'total_likes':
total_likes})
{% for post in posts %}
<form action="{% url 'like_post' photo.id %}" method="POST">
{% csrf_token %}
{{ post.likes.count }} # this would count and give you the total number of likes
<button type="submit", name="post_id" value="{{ post.id }}">Touch</button>
</form>
{% endfor %}
# OR
{% for post in posts %}
<form action="{% url 'like_post' photo.id %}" method="POST">
{% csrf_token %}
{{ total_likes }} # this would count and give you the total number of likes
<button type="submit", name="post_id" value="{{ post.id }}">Touch</button>
</form>
{% endfor %}

Django: How to add another form to my homepage when the homepage already has a template

On my homepage(http://127.0.0.1:8000/) I created a template and its function in views.py and the URL of the homepage directs to it, however, there is a form that I want also to show on the homepage.
views.py:
def index(request):
template = loader.get_template('tracker/index.html')
hours_grouped_project =
LogHours.objects.all().order_by('proj_assignment__project__name', 'day')
context = {
'hours_grouped_project':hours_grouped_project,
}
return HttpResponse(template.render(context,request))
def form(request):
if request.method== 'POST':
form = LogHoursForm(request.POST)
if form.is_valid():
day = form.cleaned_data['day']
hours = form.cleaned_data['hours']
developer = form.cleaned_data['developer']
project = form.cleaned_data['project']
proj_assignment=ProjectAssignment.objects.create(
developer=developer,project=project)
LogHours.objects.create(day=day,hours=hours,
proj_assignment= proj_assignment)
else:
form = LogHoursForm()
return render(request, 'tracker/form.html',{'form': form})
the index is for the template displayed on the homepage, and the form is for the form.py.
form.py
class LogHoursForm(forms.Form):
day = forms.DateField()
hours = forms.DecimalField(max_digits=10, decimal_places=2)
developer = forms.ModelChoiceField(queryset=Developer.objects.all())
project = forms.ModelChoiceField(queryset=Project.objects.all())
and here is the URL: urlpatterns = [
path('', views.index, name='index'),]
the form.html is
<h1> LogHours Form</h1>
<hr>
<form action="" method="post">
{% csrf_token %}
{{form}}
<input type="submit">
</form>
and the index.html:
<ul>
<b>Logged hours grouped by project:</b>
{% for obj in hours_grouped_project %}
<li>
{% ifchanged obj.proj_assignment %}
<b>Project name:</b>
{{obj.proj_assignment|linebreaks}}
{% endifchanged %}
<i>Sorted Date: </i>
{{obj}}
</li>
{% endfor %}
</ul>
In your function index(request):
def index(request):
if request.method=='POST':
form(request)
else:
template = loader.get_template('tracker/index.html')
hours_grouped_project = LogHours.objects.all().order_by('proj_assignment__project__name', 'day')
form = LogHoursForm()
context = {
'hours_grouped_project': hours_grouped_project,
'form': form,
}
return HttpResponse(template.render(context, request))
Then, you can render the form from your index.html like this.
...
<form action="" method="post">
{% csrf_token %}
{{form}}
<input type="submit">
...

Django booleanfield modelform

So I'm making a to-do list and I made a booleanfield modelform which has attribute "complete". I want that user to check it when it's complete and I tried wriring if task.complete == True cross out the item and it didn't work(it only worked when I checked it from the admin panel). Then I tried form.complete instead of task.complete and it doesn't do anything.
models:
class Task(models.Model):
title = models.CharField(max_length=200)
complete = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
forms:
from .models import *
class TaskForm(forms.ModelForm):
title = forms.CharField(widget= forms.TextInput(attrs={'placeholder':'Add new task...'}))
class Meta:
model = Task
fields = '__all__'
html:
<div class="main-container">
<form method="POST" action="/">
{% csrf_token %}
<input type="submit"/>
{{ form.title }}
</form>
{% for task in tasks %}
{{ form.complete }}
{% if form.complete == True %}
<h1><strike>{{task.title}}</strike></h1>
{% else %}
<h1>{{task.title}}</h1>
{% endif %}
{% endfor %}
</div>
views:
def index(request):
tasks = Task.objects.order_by('-created')
form = TaskForm()
if request.method == 'POST':
form = TaskForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
context = {
'tasks': tasks,
'form': form,
}
return render(request, 'to-do.html', context)
There are some problems with your code I don't know how to explain. Try this. It should work.
<div class="main-container">
<form method="POST" action="/"> # create new task
{% csrf_token %}
{{ form.title }}
<input type="submit" name="new-task"/>
</form>
<form method="post"> # update task status
{% csrf_token %}
{% for task in tasks %}
{% if task.complete %}
<input type="checkbox" name="if_completed" checked value="{{ task.pk }}">
<h1><strike>{{task.title}}</strike></h1>
{% else %}
<input type="checkbox" name="if_completed" value="{{ task.pk }}">
<h1>{{task.title}}</h1>
{% endif %}
{% endfor %}
<input type="submit" name="update-task"/>
</form>
</div>
view.py (Only for form, add your other code with it)
from django.http import HttpResponseRedirect
from django.urls import reverse
def index(request):
tasks = Task.objects.order_by('-created')
form = TaskForm()
if request.method == 'POST':
if 'new-task' in request.POST:
form = TaskForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('home')) # replace home with url name where you want to redirect
elif 'update-task' in request.POST:
task_pk = request.POST.getlist("if_completed")
for i in task_pk:
Task.objects.filter(pk=i).update(complete=True) # I have replace pk with i here
return HttpResponseRedirect(reverse('home')) # replace home with url name where you want to redirect
context = {
'tasks': tasks,
'form': form,
}
return render(request, 'to-do.html', context)
in forms.py
class TaskForm(forms.ModelForm):
class Meta:
model = Task
fields = ('title',)
widgets = {
'title': forms.TextInput(attrs={'placeholder':'Add new task...'})
}
This should work. There may be be some error because of typos or indentation. Let me know if you get any issue
def index(request):
tasks = Task.objects.order_by('-created')
form = TaskForm()
context = {
'tasks': tasks,
'form': form,
}
if request.method == 'POST':
if 'new-task' in request.POST:
form = TaskForm(request.POST)
if form.is_valid():
form.save()
elif 'update-task' in request.POST:
task_pk = request.POST.getlist("if_completed")
for i in task_pk:
Task.objects.filter(pk=pk).update(complete=True)
return render(request, 'to-do.html', context)

django model forms does'nt save the data

i want to create a todolist app with django.
i created a form for list model but when the user click on submit to submit a list, the form is'nt saved, why?
this is views.py
i have created an instance of the form and set the user field to it and then save the instance but fact it does'nt
def index(request):
if request.user.is_authenticated:
user_ = User.objects.get(username=request.user.username)
lists = user_.user.all()
form = listForm()
if request.method == "POST":
form = listForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
return HttpResponseRedirect(reverse("index"))
context = {'lists':lists, 'form':form}
return render(request, 'todolists/index.html', context)
else:
return render(request, 'todolists/login.html')
this is index template
{% extends "todolists/layout.html" %}
{% block body %}
{% if user.is_authenticated %}
<div class="center-column">
<form method="POST" action="{% url 'index' %}">
{% csrf_token %}
{{form.title}}
<input type="submit" class="btn btn-info">
</form>
<div class="todo-list">
{% for list in lists %}
<div class="item-row">
<a class="btn btn-sm btn-info" href="{% url 'update' list.id %}">update</a>
<a class="btn btn-sm btn-danger" href="{% url 'update' list.id %}">delete</a>
<span>{{list}}</span>
</div>
{% endfor %}
</div>
</div>
{% endif %}
{% endblock %}
this is urls.py
from django.urls import path
from .import views
urlpatterns = [
path('', views.index, name='index'),
path('update/<str:id>/', views.update, name='update'),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
]
this is models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
pass
class list(models.Model):
title = models.CharField(max_length=200)
finished = models.BooleanField(default=False)
timestamps = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user")
def __str__(self):
return self.title
here is the form code
class listForm(forms.ModelForm):
title= forms.CharField(label=mark_safe("<span style='color:white;'>Title:</span>"),
widget= forms.TextInput(attrs={'placeholder':'Add new task...', 'class':'form-control'}))
finished= forms.BooleanField(label=mark_safe("<span style='color:white;'>Finished:</span>"),
widget= forms.CheckboxInput(attrs={'style':'width:25px;'}))
class Meta:
model = list
fields = '__all__'
Try updating your template file {{ form.title }} to {{ form }} as mentioned in django docs here is the link
Update your forms.py file if want only title field in the HTML
class listForm(forms.ModelForm):
title= forms.CharField(label=mark_safe("<span style='color:white;'>Title:</span>"),
widget= forms.TextInput(attrs={'placeholder':'Add new task...', 'class':'form-control'}))
class Meta:
model = list
fields = ('title', )

View didn't return an HttpResponse

My project is here github Project
I'm getting this error.
ValueError at /salesapp/add/ashton-aged-maduro/
The view salesapp.views.add_CartItem didn't return an HttpResponse object. It returned None instead.
I get this error when I click the 'Add to Cart' button on my singleproduct.html template which calls the ProductAddToCart form. The view is add_CartItem.
I also get the error Field is required when I don't initially set the form values. I'm just stuck now.
This is models.py
class Product(models.Model):
itemid = models.CharField(max_length=128, unique=True)
itemname = models.CharField(max_length=128)
brand = models.CharField(max_length=128)
image = models.ImageField(upload_to='static/images/')
notes = models.CharField(max_length=250)
price = models.IntegerField()
slug = models.SlugField(unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.itemname)
super(Product, self).save(*args, **kwargs)
def __str__(self):
return self.itemname
class CartItem(models.Model):
cart_id = models.CharField(max_length=50)
date_added = models.DateTimeField(auto_now_add=True)
quantity = models.IntegerField(default=1)
itemid = models.ForeignKey('Product', unique=False)
class Meta:
db_table = 'cart_items'
ordering = ['date_added']
def name(self):
return self.product.name
My forms.py
class ProductAddToCartForm(forms.ModelForm):
cart_id = forms.CharField(max_length=50)
date_added = forms.DateTimeField()
quantity = forms.IntegerField()
slug = forms.CharField(widget=forms.HiddenInput(), required=False)
#itemid = models.ForeignKey('Product', unique=False)
class Meta:
model = CartItem
fields = ('cart_id', 'date_added', 'quantity', 'slug', 'itemid', )
My views.py
def add_CartItem(request, product_name_slug):
print('In add_CartItem --------------------')
form = ProductAddToCartForm(request.POST)
p = Product.objects.get(slug=product_name_slug)
form = ProductAddToCartForm(initial={'cart_id': 123, 'date_added':date.date.today(), 'quantity': 1, 'slug':p.slug, 'id':p.id, 'itemid':p.itemid})
form.save(commit=False)
print(form)
print(p.slug)
print(p.id)
print(p.itemid)
if form.is_valid():
print(p)
print('In form.is_valid()--------------------------------')
ci = CartItem.objects.create(cart_id=1, date_added=date.date.today(), quantity=1, itemid=p)
form.save(commit=True)
return index(request)
else:
print(form.errors) #return render(request, 'salesapp/errors.html', {'form': form})
My urls.py
from django.conf.urls import url
from salesapp import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'about/', views.about, name='about'),
url(r'customers/', views.customers, name='customers'),
url(r'products/', views.products, name='products'),
url(r'^add_product/$', views.add_product, name='add_product'),
url(r'^add_customer/$', views.add_customer, name='add_customer'),
url(r'items/(?P<product_name_slug>[\w\-]+)/$', views.show_product, name='show_product'),
url(r'^add/(?P<product_name_slug>[\w\-]+)/$', views.add_CartItem, name='add_CartItem'),
#url(r'^cart/$', views.show_cart, name='show_cart'),
#url(r'^register/$', views.register, name='register'),
#url(r'^login/$', views.user_login, name='login'),
#url(r'^logout/$', views.user_logout, name='logout'),
#url(r'^restricted/', views.restricted, name='restricted'),
]
and my template where I want to display the ProductAddToCartForm but add a product to the CartItem table.
<!DOCTYPE html>
{% extends 'salesapp/base.html' %}
{% load staticfiles %}
{% block title_block %}
{{ product.itemname }}
{% endblock %}
{% block body_block %}
<div>
<div>
<ul style="list-style:none; text-align:center;">
<li style="float:left; width:25%; margin:20px;">
<img src="/{{ product.image }}"/>
<div>
<b>{{ product.itemname }}</b><br/>
Price per cigar:<br/>
<b>${{ product.price }}</b>
<p>{{ product.notes }}</p>
</div>
<form method="post" action="/salesapp/add/{{ product.slug }}/" class="cart">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text }}
{{ field }}
{% endfor %}
<br />
<input type="submit" value="Add To Cart" name="submit" alt="Add To Cart" />
</form>
<div class="cb"></div>
</li>
</ul>
</div>
<!-- More code -->
</div>
{% endblock %}
A view function in django should either return a json or a dict or can return a Webpage
You can either do one of following
1) return a json or dict
return {"value1":"value","value2":"value"}
2)redirect to a web page
return redirect('/some/url/')
3)return Http response
return HttpResponse(status=<status code>,content="some content")
4)render a template
t = loader.get_template('myapp/index.html')
c = {'foo': 'bar'}
return HttpResponse(t.render(c, request),
content_type='application/xhtml+xml')
Because you did not return any response to the view,
According to the docs
A view function is simply a Python function that
takes a Web request and returns a Web response.
You need to return to use render method for initial rendering of form and for redirection to another view you can use redirect method of Django.
A view function must return an HttpResponse. For example, if the process was successfull and you dont want to return anything, you can return HttpResponse(status=200)
When a view handles forms, you have to split GET and POST requests. In the GET part you need to instantiate the form without data. In the POST part you fill the form with request.POST data. And this data must have ALL mandatory fields. A typical view function scheme to handle a form is the folowing:
def view(request):
if request.method == "GET":
form = MyForm()
return ...
if request.method == "POST":
form = MyForm(request.POST)
form.save()
return ...
In your template, you have to show all form fields. Then, all form fields will be passed with the request. If you dont, you need to fill the form fields in the view.
first delete the prints, almost when you make a question, are useless in Django
def add_CartItem(request, product_name_slug):
form = ProductAddToCartForm(request.POST)
if request.method == 'POST':
if form.is_valid():
ci = CartItem.objects.create(cart_id=1, date_added=date.date.today(), quantity=1, itemid=p)
ci.save()#you save your model changes, not your form
return HttpResponseRedirect(reverse('your:url'))#your return the success url or the same
else:
#here error, if form isn't valid
else:
form = ProductAddToCartForm(request.POST)
return render(request, 'your/template.html', {'form': form})
That is the correct way to work with forms in Django, first you must make a if statement asking to the browser if is a post request or a normal request, if is post request, take the data from the forms and are adding to the database, if not, Django return a empty template form.
Let me know if you problem solve