when I add a video from addvideo templates file its say: The 'file' attribute has no file associated with it. I want a user to be able to upload video.
when I add videos from my admin it's working fine, but when I added it from my form page its added the video in admin but its does not show the video in the home page and it's highlight my video tag src="{{video.file.url}}" saying: 'file' attribute has no file associated with it.
this is my models:
class Video(models.Model):
file = models.FileField(upload_to='file', null=False, blank=False)
this is my views:
def addvideo(request):
if request.method == 'POST':
file = request.FILES.get('video')
videos = Video.objects.create(
file=file
)
return redirect('home')
return render(request, 'addvideo.html')
def home(request):
videos = Video.objects.all()
return render(request, 'home.html', {'videos': videos})
this is my addvideo templates:
<div class="col-md-5">
<form action="" method="POST">
{% csrf_token %}
<div class="card">
<div class="form-group m-3">
<label>Upload Your Video</label><br><br>
<input required name="video" type="file" class="form-control-file">
</div>
<button type="submit" class="btn btn-primary">Post</button>
</div>
</form>
</div>
this is my home templates:
<div class="container">
{% for video in videos %}
<div class="row justify-content-center">
<video style="height: 500px; width: 500px;" controls src="{{video.file.url}}">
</video>
</div>
{% endfor %}
</div>
In order to submit a file with a HTML form, you need to specify how it will send the file content: you need to specify the enctype="…" [MozillaDev]. You can do this with:
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="card">
<div class="form-group m-3">
<label>Upload Your Video</label><br><br>
<input required name="video" type="file" class="form-control-file">
</div>
<button type="submit" class="btn btn-primary">Post</button>
</div>
</form>
Related
django returns MultiValueDictKeyError at /
'q' in my dashboard template when I'm trying to add search functionality into my app. I want when a user type something on the search input to return the value that user searched for. but i endup getting an error when i try to do it myself.
MultiValueDictKeyError at /
'q'
def dashboard(request):
photos = Photo.objects.all()
query = request.GET['q']
card_list = Photo.objects.filter(category__contains=query)
context = {'photos': photos, 'card_list':card_list}
return render(request, 'dashboard.html', context)
<div class="container">
<div class="row justify-content-center">
<form action="" method="GET">
<input type="text" name="q" class="form-control">
<br>
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
<br>
<div class="container">
<div class="row justify-content-center">
{% for photo in photos reversed %}
<div class="col-md-4">
<div class="card my-2">
<img class="image-thumbail" src="{{photo.image.url}}" alt="Card
image cap">
<div class="card-body">
<h2 style="color: yellowgreen; font-family: Arial, Helvetica,
sans-serif;">
{{photo.user.username.upper}}
</h2>
<br>
<h3>{{photo.category}}</h3>
<h4>{{photo.price}}</h4>
</div>
<a href="{% url 'Photo-view' photo.id %}" class="btn btn-warning btn-
sm m-1">Buy Now</a>
</div>
</div>
{% empty %}
<h3>No Files...</h3>
{% endfor %}
</div>
</div>
try this
query = request.GET['q']
query = request.GET.get('q', '') # use get to access the q
The get() method returns the value of the item with the specified key.
I will create multi image add page. But the following error occurs. Could your help me? I think mistake in views.py. I'm not sure.
Note : It's frustrating that Stackoverflow asks for a long explanation.
error:
AttributeError at /en/projects/multiimageadd/10/
'bytes' object has no attribute '_committed'
#login_required
#permission_required('is_superuser')
def MultiImageAdd(request, id):
blog = BlogModel.objects.filter(id=id).first()
if request.method == 'POST':
images = request.FILES['images']
for image in images:
Images.objects.create(project=project, image=image)
return redirect("home")
return render(request,"multiImage.html")
<div class="container-fluid">
<div class="row">
<div class="col-sm-12">
<div class="card">
<div class="card-header">
</div>
<div class="card-body">
<form class="needs-validation" method="POST" action="" enctype="multipart/form-data"
novalidate="">
{% csrf_token %}
<div class="row">
<div class="col-sm-12">
<div class="form-group row">
<label for="id_images" class="col-xl-3 col-md-4">Images:</label>
<span class="form-control col-md-8">
<input required type="file" name="images" id="id_images" multiple>
</span>
</div>
</div>
</div>
<div class="pull-right">
<button class="btn btn-primary" type="submit">Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
models.py
class Images(models.Model):
blog = models.ForeignKey(BlogModel, related_name='blogmodel', on_delete=models.CASCADE, blank=True,null=True)
image = models.ImageField(blank=False, null=True)
You should enumerate over the file handlers, so obtain the handlers with .getlist(…) [Django-doc]:
images = request.FILES.getlist('images')
for image in images:
Images.objects.create(project=project, image=image)
I have a custom form validation that runs on my popup window form. If the form validation occurs i get a bad request error which is what i have programmed in my views.py . How do i render it so the user stays on the form and the validation message displays. Thanks for the help. Here is my code.
#login_required
def K8_Points_Classroom(request):
#context_from_k8_points = request.session['k8_points_context']
if request.method == 'POST':
form = K8Points_ClassroomForm(request.POST)
if form.is_valid():
form.save(commit=False)
form.save()
class_name = form.cleaned_data.get('class_name')
getstudents = Student.objects.filter(class_name = class_name)
students = getstudents.all()
form = K8Points_ClassroomForm()
context = {'form': form ,'students' : students, 'class_name': class_name,}
return render(request,'points/k8_points_classroom.html', context)
else:
return HttpResponseBadRequest("Bad Request")
else:
return render(request, 'points/k8_points_classroom.html', {'form': form} )
Updated form.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% crispy K8Points_ClassroomForm %}
{% load static %}
{% block content %}
<br>
<h2>{% load static %}
<img src="{% static 'forms/star.png' %}" alt="chain" height="62" width="62"> {{class_name}}</h2>
<br>
<br>
<form action="/points/k8_points_classroom" method="POST">
{% csrf_token %}
<!-- Start Date -->
<div class="container">
<div class="container">
<div class='row'>
<div class="col-4">
<p> Recording Data as User : {{user.username}} </p>
</div>
</div>
<div class='row'>
<div class = "col-2">
{{form.date|as_crispy_field }}
</div>
<div class = "col-2">
{{form.week_of|as_crispy_field }}
</div>
<div class = "col-2">
{{form.day|as_crispy_field }}
</div>
</div>
</div>
</form>
<div class="jumbotron" align="middle">
<img src="{% static 'forms/levelup.png' %}" alt="levelup" height="120" width= "120">
<h1>My Students</h1>
<!-- Line Break -->
<hr style="border: 1px solid black;"/>
<!-- Line Break -->
<div class="row mb-3">
{% for i in students%}
<div class="col-md-4 themed-grid-col"><h2>{{i.student_name}}</h2>
<p align="left"> Today's Score: {{total}}</p>
<h4>
<button type="button" class="btn btn-primary btn-lg btn-block" data-toggle="modal"
data-target="#PointsBox{{ student.pk }}">Level Up
</button>
</h4>
<div id="PointsBox{{ student.pk }}" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<img src="{% static 'forms/star.png' %}" align="left" alt="chain" height="42"
width="42">
<h4 class="modal-title">Points Confirmation </h4>
<button type="button" class="close" data-dismiss="modal"> ×</button>
</div>
<div class="modal-body">
<h6>
<div class="modal-body">Please add the selected points for the current
student.</div>
</h6>
<form action="/points/k8_points_classroom" method="POST">
{% csrf_token %}
<div class="form-row" align='left'>
<div class="col-7">
{{form.class_name|as_crispy_field }}
<input type="student_name" class="form-control" value ="{{i}}" >
{{form.time_frame|as_crispy_field }}
</div>
</div>
<div class="form-row">
<div class="col-3" align='left'>
{{form.behavior|as_crispy_field }}
{{form.academic|as_crispy_field }}
<button type="submit" class="btn btn-success" ><i
class="fas fa-star"></i> Level Up
</button>
</div>
</div>
</div>
<div class="modal-foot"></div>
</div>
</div>
</div>
</div>
</form>
{% endfor %}
{% endblock %}
You can't return a bad response if the form is invalid. Instead, render the page again with the invalid form and in the temolate you will be able to render the errors. Try starting rendering the form just using {{ form.as_p }} and you will see the errors. The form errors are in form.errors and each field has its own errors, you can access to them form.field.erorrs
if request.method == 'POST':
form = K8Points_ClassroomForm(request.POST)
if form.is_valid():
form.save(commit=False)
form.save()
class_name = form.cleaned_data.get('class_name')
getstudents = Student.objects.filter(class_name = class_name)
students = getstudents.all()
form = K8Points_ClassroomForm()
context = {'form': form ,'students' : students, 'class_name': class_name,}
return render(request,'points/k8_points_classroom.html', context)
return render(request, 'points/k8_points_classroom.html', {'form': form} )
I want to open a particular record in html template in update mode for which i want every value which was inserted before for this record be in those field, i got every required value in field for text field but in file field which contains image ,it shows no file selected where as i want the image file name(url) in there.
I havent used django form rather i used normal bootstrap forms.
models.py
from django.db import models
from django.contrib.auth.models import User
class Product(models.Model):
title = models.CharField(max_length=255)
pub_date = models.DateTimeField()
body = models.TextField()
image = models.ImageField(upload_to='images/') # i m facing problem for this field
icon = models.ImageField(upload_to='images/') # i m facing problem for this field as well
url = models.TextField()
votes_total = models.IntegerField(default=1)
hunter = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return self.title
def summary(self):
return self.body[:100]
def short_pub_date(self):
return self.pub_date.strftime('%b %e %Y')
#
views.py
def myproducts_update(request,product_id):
product = get_object_or_404(Product,pk=product_id)
print(product.image) # this prints the name of the file (images/37003.jpeg)
return render(request,'products/myproducts_update.html',{'product':product})
templates(myproducts_update.html)
{% extends 'base.html' %}
{% block content %}
{% if error %}
{{error}}
{% endif %}
<br>
<br>
<div class="container">
<div class="jumbotron">
<h2>Update Product</h2>
<form action="{% url 'create' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<label for="title">Title:</label>
<input type="text" class="form-control" id="email" value={{product.title}} placeholder="please enter title" name="title" required>
</div>
<div class="form-group">
<label for="body">Description:</label>
<input type="text" class="form-control" id="body" value={{product.body}} placeholder="Description" name="body" required>
</div>
<div class="form-group">
<label for="url">URL:</label>
<input type="text" class="form-control" id="url" value={{product.url}} placeholder="please enter url" name="url" required>
</div>
<br>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="icon">
<strong>Icon:</strong></label>
<input type="file" id="icon" name="icon" value={{product.icon}} required>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="url">
<strong>Image:</strong></label>
<input type="file" id="image" placeholder="please enter url" name="image" value={{product.image}} required>
</div>
</div>
</div>
<br>
<input type="submit" value="Update Product" class="btn btn-primary">
</form>
</div>
</div>
{% endblock %}
Link which contains image of form where i have problem
I am having trouble in getting the url of the image in the templates,guys please help me
Thanks in advance!
Try something like this in your <form>:
<div class="margintop50px">
<img {% if object.image %} src="{{ object.image.url }}" {% else %} alt="You have no image." {% endif %}>
<input type="file" name="image" accept="image/*">
</div>
UPDATE:
I just checked your views.py. Sorry for not noticing sooner, but your myproducts_update() function never .save()'s anything, so nothing will show because of that. Try changing that function to something like the following. It assumes the product has already been created somewhere else because I don't know of any other views you made to get this far (maybe you originally added all pics/text from the admin panel? And personally, I would change the names of your function(s) because your form goes to 'create', but the function you showed states that this is about updating it, and that's generally not a clear path to follow when designing it because createing something is different from 'update'ing it. So if the following still doesn't work, I'll need to see your 'create' view, and the urlpatterns for all these functions).
Either way, there are better ways to improve the following (such as what I talked about above), but this is all I can give you without knowing that stuff:
views.py
def myproducts_update(request,product_id):
product = get_object_or_404(Product,pk=product_id)
if request.method == 'POST':
product.body = request.POST.get('body', False)
product.title = request.POST.get('title', False)
product.url = request.POST.get('url', False)
product.icon = request.FILES.get('icon', False)
product.image = request.FILES.get('image', False)
product.save()
return render(request,'products/myproducts_update.html',{'product':product})
And then use the example template above to get it to show on that page.
I want to create a Django form that allows users to select options from a dropdown menu, but I am getting a value error:
ValueError: need more than 1 value to unpack
Form:
class DropdownForm(forms.Form):
def __init__(self,*args,**kwargs):
choices = kwargs.pop('choices')
label = kwargs.pop('label')
super(DropdownForm,self).__init__(*args,**kwargs)
self.fields['selected'].label = mark_safe(label)
self.fields['selected'].choices = choices
selected = forms.ChoiceField(widget=forms.Select(attrs={'class':"form-control text-center"}))
View.py:
form_rate = DropdownForm(choices=[("HIGH","HIGH")],label="RATE",prefix="Rate")
form_pass_setup = DropdownForm(choices=[("AUTO","AUTO"),("MANUAL","MANUAL")],label="Pass Setup",prefix="pass_setup")
form_dict.update({'form_rate':form_rate,'form_pass_setup':form_pass_setup})
return render(request,'Nominal.html',form_dict)
Template:
<form action="/InterfaceApp/Nominal_Request/" method="post" class="form">
{% csrf_token %}
<div class="panel-body text-center">
<div class="row pad_forms">
<div class="col-xs-3">
{% bootstrap_form form_rate %}
</div>
<div class="col-xs-3">
{% bootstrap_form form_pass_setup %}
</div>
</div>
<br><br>
<button type="submit" class="btn btn-primary center-block" value="Submit" name="Single">
{% bootstrap_icon "fire" %} Generate a Single Requests
</button>
</div>
</form>
Can anyone tell me why I'm getting this value error?
The problem might occur cause you have not set the required argument choices for your ChoiceField.
Here is a link to the docs: https://docs.djangoproject.com/en/1.8/ref/forms/fields/#choicefield.