Im trying to upload images using Dropzone.js .
There doesnt seem to be any current tutorials for Dropzone although i used this link: https://amatellanes.wordpress.com/2013/11/05/dropzonejs-django-how-to-build-a-file-upload-form/
Essentially what i want to do is , The user uploads multiple images . a hotel_id is attached to the images and stored in the hotelphotos table as a url which is unique each time .
MY code
Models.py
class Photo(models.Model):
hotel = models.ForeignKey(Hotels,on_delete=models.CASCADE)
path = models.FileField(upload_to='files/%Y/%M/%d)
forms.py
class PhotosForm(forms.ModelForm):
class Meta:
model = Photo
fields = ['path']
views.py
def uploadPhoto(request,hotelid):
if request.method == 'POST':
form = PhotosForm(request.POST,request.FILES)
if form.is_valid():
new_file = Photo(path = request.FILES['file'] , hotel_id = hotelid)
new_file.save()
else:
form = PhotosForm()
hotelid = hotelid
data = {'form': form, 'hotelid':hotelid}
return render(request, template , data)
The form
<form class="dropzone" action="{% url 'ManageHotels:uploadPhoto' hotelid %} method = "POST">
</form>
Files uploaded dont get created and the url also doesnt add to the database.
Hope someone can help!
Related
I'm new to Django and creating a way for users to upload an image onto a post. Then the image should be visible on each individual post's page.
So far in my 'create' function users can successfully create a post and upload a photo. The photo is uploaded into my project but it is still not displaying at all. Any help is greatly appreciated.
I think the issue is how the class in views.py, and the html in index.html is written. Just not sure how to fix.
views.py to create the post:
def create(request):
if request.method == 'GET':
context = {
'form': CreateForm(),
'form1': CategoryForm(),
'img_form': ImgForm(),
}
return render(request, "auctions/create.html", context)
else:
form = CreateForm(request.POST, request.FILES)
form1 = CategoryForm(request.POST, request.FILES)
img_form = ImgForm(request.POST, request.FILES)
if form.is_valid():
title = form.cleaned_data['title']
description = form.cleaned_data['description']
starting_bid = form.cleaned_data['starting_bid']
if form1.is_valid():
category = form1.cleaned_data['category']
if img_form.is_valid():
image = img_form.cleaned_data['image']
auctionCreated = Listings.objects.create(
title=title,
description=description,
starting_bid=starting_bid,
)
categoryCreated = Categories.objects.create(
category=category,
)
ImageCreated = Img.objects.create(
image=image,
)
return redirect('index')
views.py - this should show a list of each post (on the homepage) and each image should be visible but the image is not appearing:
def index(request):
items = Listings.objects.all()
images = Img.objects.all()
return render(request, "auctions/index.html", {
'items': items,
'images': images,
})
views.py to display image:
class ImgDisplay(DetailView):
model = Img
template_name = 'listing.html', 'index'
context_img_name = 'pic'
models.py
class Img(models.Model):
image = models.ImageField(upload_to='images/')
forms.py
class ImgForm(ModelForm):
class Meta:
model = Img
fields = '__all__'
index.html
{% for i in items %}
{% for photo in images %}
<img src="{{pic.image.url}}" class="card-img" alt="...">
{% endfor %}
<a href="{% url 'listingpage' i.id %}"><button class="btn btn-primary">Bid Now!
</button></a>
{% endfor %}
your index.html parameters are not correct. you are passing images as context parameter from index view. But when you are using for-loop in index.html you are using pic.image.url as a image source which should be photo.image.url.
if you want to show images by using ImgDisplay(DetailView) then you can use pic.image.url and also need to correct the template_name.
`template_name` = 'listing.html', 'index.html'
How can I submit 3 images at once with a single input.
class Image(models.Model):
imageuploader_profile = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True, blank=True)
image = models.FileField(upload_to ='pictsagram/')
I do not think this is too complicated. You just need a form with a file input having the multiple attribute and then save all the files in your view.
E.g. a very basic example
#forms.py
class ImageForm(forms.Form):
images = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
Your html form
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
<button type="submit">Upload</button>
</form>
And then create your images in your view, using getlist on the field
# views.py
def images_upload(request):
if request.method == 'POST':
form = ImageForm(request.POST, request.FILES)
if form.is_valid():
for img in request.FILES.getlist('images'):
Image.objects.create(imageuploader_profile=request.user, image=img)
return redirect('images_upload')
form = ImageForm()
context = {'form': form}
return render(request, 'images.html', context)
So, I think this is an instance of where you need to make use of the ManyToMany relationship field, creating a new model instance which stores one image, e.g., (and this is a simplistic version of something like what you would need).
from django.db import models
class ImageAttachment(models.Model):
file = models.FileField(upload_to ='pictsagram/')
Then, in your Image model:
class Image(models.Model):
imageuploader_profile = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True, blank=True)
images = models.ManyToManyField(ImageAttachment)
The user will then pass up X number of images to the server, at which point you will create multiple images, and append them to the images field for the Image model.
As code organisation goes, I would also consider renaming you Image model, as it is actually storing multiple images ...
models.py
class FileUpload(models.Model):
File_Name = models.CharField(max_length=255, blank=True)
File_path = models.FileField(upload_to='')
Description = models.CharField(max_length=255, blank=True)
Upload_Date = models.DateTimeField(auto_now_add=True)
forms.py
class FileUploadForm(forms.Form):
class Meta:
model = FileUpload
File_Name = forms.CharField(label="File Name",max_length=255)
Description = forms.CharField(label="Description", max_length=255)
I'm new in Django.I need help. How to upload images in the database and view those images? Thanks in advance!
here paths are stored in database and images are stored in a folder. But I don't need that. I want to save images and path to the database and I need to view that image. Please help!
views.py:
def uploadfile(request):
print('inside upload logic')
if request.method == 'POST':
form = FileUploadForm(request.POST, request.FILES)
if form.is_valid():
# ImageUpload(request.FILES['File_Name'])
myfile = request.FILES['File_Name']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(filename)
newdoc = FileUpload(File_Name=myfile.name, File_path=uploaded_file_url, Description=request.POST['Description'])
newdoc.save()
#return HttpResponse("File uploaded successfuly")
return render(request, 'Login/fileupload.html')
else:
form = FileUploadForm()
return render(request, 'Login/fileupload.html', {
'form': form
})
You normally shouldn't store the image data in your database. If you need to upload and store images, use the ImageField or FileField and follow the instructions from the docs to save the image. The only thing you need to do is:
form = FileUploadForm(request.POST, request.FILES)
if form.is_valid():
uploaded_file = FileUpload(
File_path=request.FILES['File_path'], # or whatever you've called the file input
File_name=form.cleaned_data['File_Name'],
Description=form.cleaned_data['Description'])
uploaded_file.save()
It would be easier to use a ModelForm in your case, then you only need to save the form:
if form.is_valid():
form.save()
This will automatically save the file in the correct way. No need to do the saving manually like you are doing.
To view the image is as simple as this:
file_upload = FileUpload.objects.get(id=34)
file_url = file_upload.File_path.url # url relative to `MEDIA_ROOT`
# or in a template
{% load static %}
{% get_media_prefix %}{{ file_upload.File_path.url }}
If you really need to store the images as binary blobs to your database (but beware that it almost never makes sense to do so), use Django's BinaryField, as described here.
This also means you will have to handle transforming the image back and forth from a binary blob to a proper image file. Consider also storing the content type (image/jpg or image/png or image/webp) since you will need that to properly re-create the file.
I am new to Django and trying to save some data from the form to the model. I want to insert into two models which have a foreign key constraint relationship (namely Idea and IdeaUpvotes) i.e. from a html template to a view.
My submit code is:
def submitNewIdea(request):
#get the context from the request
context = RequestContext(request)
print(context)
#A HTTP POST?
if request.method == 'POST':
form = submitNewIdeaForm(request.POST)
# Have we been provided with a valid form?
if form.is_valid():
# Save the new Idea to the Idea model
print(request.POST.get("IdeaCategory"))
print(request.POST.get("IdeaSubCategory"))
i = Idea( idea_heading = form["idea_heading"].value()
,idea_description = form["idea_description"].value()
,idea_created_by = form["idea_created_by"].value()
,idea_votes = form["idea_votes"].value()
,idea_category = request.POST.get("IdeaCategory") #value from dropdown
,idea_sub_category = request.POST.get("IdeaSubCategory") #value from dropdown
)
i.save()
# get the just saved id
print(Idea.objects.get(pk = i.id))
iu = IdeaUpvotes(idea_id = Idea.objects.get(pk = i.id)
,upvoted_by = form["upvoted_by"].value()
,upvoted_date = timezone.now() )
iu.save()
form.save(commit = True)
# Now call the index() view.
# The user will be shown the homepage.
return index(request)
else:
# The supplied form contained errors - just print them to the terminal.
print (form.errors)
else:
# If the request was not a POST, display the form to enter details.
form = submitNewIdeaForm()
# Bad form (or form details), no form supplied...
# Render the form with error messages (if any).
return render(request,'Ideas/Index.html',{'form' :form})
form.py --->
class submitNewIdeaForm(forms.ModelForm):
idea_heading = forms.CharField(label = "idea_heading",max_length =1000,help_text= "Please enter the idea heading.")
idea_description= forms.CharField(label = "idea_description",max_length =1000,help_text= "Please enter the idea description.",widget=forms.Textarea)
idea_created_by=forms.CharField(max_length =200, widget = forms.HiddenInput(), initial='wattamw')
idea_votes = forms.IntegerField(widget=forms.HiddenInput(), initial=1)
upvoted_by=forms.CharField(max_length =200, widget = forms.HiddenInput(), initial='abcde')
"""
#commented code
#idea_category_name = forms.CharField(label = "idea_category_name",max_length =250,help_text= "Please select an Idea Category.")
#idea_sub_category = forms.CharField(label = "idea_sub_category",max_length =250,help_text= "Please select an Idea Sub Category.")
idea_category_name = forms.ModelChoiceField(
queryset = IdeaCategory.objects.all(),
widget=autocomplete.ModelSelect2(url='category-autocomplete'))
idea_sub_category = forms.ModelChoiceField(
queryset = IdeaSubCategory.objects.all(),
widget = autocomplete.ModelSelect2(
url='subcategory-autocomplete',
forward = (forward.Field('idea_category_name','id'),)))
"""
class Meta:
model = Idea
fields = ('idea_heading','idea_description','idea_created_by','idea_votes','idea_category_name','idea_sub_category')
class Meta:
model = IdeaUpvotes
fields = ('upvoted_by',)
def __init__(self,*args,**kwargs):
super(submitNewIdeaForm,self).__init__(*args,**kwargs)
self.fields['idea_category_name'] = forms.ModelChoiceField(
queryset = IdeaCategory.objects.all(),
widget=autocomplete.ModelSelect2(url='category-autocomplete'))
self.fields['idea_sub_category'] = forms.ModelChoiceField(
queryset = IdeaSubCategory.objects.all(),
widget = autocomplete.ModelSelect2(
url='subcategory-autocomplete',
forward = (forward.Field('idea_category_name','id'),)))
I am able to print the values and see that they are passed,but I still get the following error :
Error Description
I have removed any foreign key references to the table, the fields are simple character fields.
Please help me out.
Thanks.
In the first place, your form validation is failing. It seems to me that your form template may be wrong.
The second thing is that you don't use Django forms properly. All you need to do to achieve the functionality you are looking for is to use ModelForm and let the form's save method to create the object for you. All you need to do is:
Associate your SubmitNewIdeaForm with the Idea model:
# forms.py
class SubmitNewIdeaForm(ModelForm):
class Meta:
model = Idea
fields = (
'idea_heading',
'idea_description',
'idea_created_by',
'idea_votes',
'idea_category',
'idea_sub_category'
)
Render the form
#form_template.html
<form action="{% url 'your_url' %}" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
Finally jsut check if the form is valid and call form.save() like so:
def submitNewIdea(request):
if form.is_valid():
form.save()
That's it! I hope that I helped you.
Cheers!
Finished = models.IntegerField('Finished percentage', error_messages={'required':''})
Worked for me.
I have a page where you can add a product, add a thumbnail, and add images for the product.
I am using to formsets, seen below. The problem is that images uploaded to the image formset are uploaded correctly, but images uploaded to the thumbnail formset are not uploading at all... what might I be doing wrong?
def AddProduct(request):
ImageFormSet = modelformset_factory(ProductImage,
form=ImageForm, extra=4)
ThumbnailFormSet = modelformset_factory(ProductvThumbnail,
form=ThumbnailForm)
if request.method == 'POST':
product_form = AddEditProductForm(request.POST)
image_formset = ImageFormSet(request.POST, request.FILES, prefix='images',
queryset=roductImage.objects.none())
thumbnail_formset = ThumbnailFormSet(request.POST, request.FILES, prefix='thumbnail',
queryset=ProductThumbnail.objects.none())
if product_form.is_valid() and image_formset.is_valid() and thumbnail_formset.is_valid():
product = product_form.save()
thumbnails = thumbnail_formset.save(commit=False)
for thumbnail in thumbnails:
thumbnail.product = product
thumbnail.save()
images = image_formset.save(commit=False)
for image in images:
image.product = product
image.save()
return HttpResponseRedirect('/product/')
else:
print (product_form.errors, image_formset.errors, thumbnail_formset.errors)
else:
product_form = AddEditProductForm()
image_formset = ImageFormSet(queryset=ProductImage.objects.none(), prefix='images')
thumbnail_formset = ThumbnailFormSet(queryset=ProductThumbnail.objects.none(), prefix='thumbnail')
return render(request, 'product/add.html',
{'product_form': product_form, 'image_formset': image_formset,
'thumbnail_formset': thumbnail_formset},
context_instance=RequestContext(request))
I have found a solution - my formsets seem to be fine, the issue was in my models.py. The ImageField in the ProductThumbnail model was called 'image = models.ImageField...' but it should have been called thumbnail - that is why no thumbnails were being uploaded - my for loop was not finding anything.