My Django Form Doesn't Add My Images To The Database - django

I Tried To Add An Image To My Database But I Can Only Insert It Manually In My Admin Panel, It Doesn't Add It Automatically From My Form
This Is My models.py
option1photo = models.ImageField(null=True, blank=True)
option2photo = models.ImageField(null=True,blank=True)
option3photo = models.ImageField(null=True,blank=True)
And My forms.py
class AddpollForm(forms.ModelForm):
class Meta:
model = PollOptions
fields = ['option1photo','option2photo','option3photo']
And My views.py
polloptions_form = AddpollForm()
if request.method == 'POST':
polloptions_form = AddpollForm(request.POST)
if polloptions_form.is_valid():
polloptions = polloptions_form.save(commit=True)
return redirect('home')

Any files in the form are put in request.FILES by Django. Also one should make sure their form tag has the following set: enctype="multipart/form-data" if they are submitting file data.
Your view should be like:
polloptions_form = AddpollForm()
if request.method == 'POST':
polloptions_form = AddpollForm(request.POST, request.FILES)
if polloptions_form.is_valid():
polloptions = polloptions_form.save(commit=True)
return redirect('home')
And your form tag when you are uploading files should be like:
<form method="post" enctype="multipart/form-data">

Related

How to upload file in django

this might be a pretty stupid question. Also I am new to django. But I was trying to create a basic file upload approach with django where user uploads a file and it gets stored into the defined media path (or whatever that it's called) and that the file size, name, and some other attributes that are needed can be stored into the database. So I have the model ready which will help you understand the question better.
class Document(models.Model):
file_uid = models.CharField(max_length = 16)
file_name = models.CharField(max_length = 255)
file_size = models.CharField(max_length = 255)
file_document = models.FileField(upload_to='uploaded_files/')
uploaded_on = models.DateTimeField(auto_now_add=True)
uploaded_by = models.CharField(max_length=16)
Now it's clearly plain that we don't need to create all the fields in the form and that most them can be received from the file itself (like the name, size). for other attrs like uid and uploaded by those also will be added by the backend. So that's where I am stuck. I have searched for 2 days straight and still couldn't find a proper solution.
As of now this is my views.py
def uploadView(request):
if(request.method == 'POST'):
form = FileUploadForm(request.POST, request.FILES)
uploaded_file = request.FILES['uploaded_file']
file_dict = {
'file_uid' : get_random_string(length=10),
'file_name' :uploaded_file.name,
'file_size' : uploaded_file.size,
'file_document' : request.FILES['uploaded_file'],
'uploaded_by' : get_random_string(length=10)
}
form = FileUploadForm(data=file_dict)
if form.is_valid():
form.save()
return HttpResponse("You reached here")
else:
return HttpResponse("Your form is invalid")
else:
form = FileUploadForm(request.POST, request.FILES)
return render(request, 'function/upload.html', {
'form':form
})
I don't know if this is correct but as of know the form.isvalid() is false.
here's my forms.py
class FileUploadForm(forms.ModelForm):
file_document = forms.FileField(widget=forms.FileInput(attrs={'name':'uploaded_file'}))
class Meta:
model = Document
fields = ('file_uid', 'file_name', 'file_size', 'file_document', 'uploaded_by')
and my upload page section looks like this
<body>
<h1>Upload a file</h1>
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="uploaded_file">
<button type="submit">Upload</button>
</form>
</body>
If you can mercifully guide me into a proper way of doing this i'll be really gratefull.
Before solution, Here are few issues i found in your code
Major issue is how you tried to update the name of your file_document input, it doesn't work this way. confirm this by inspecting in devtools.
Checkout my answer here to update name attribute of django input form field.
Without updating this, you are not getting file from form.
Not issues just something i would like to point out
def uploadView(request):
if(request.method == 'POST'):
form = FileUploadForm(request.POST, request.FILES)
# your code in between, here the above form is never used and the overridden by the form in next line so why assigning it
form = FileUploadForm(data=file_dict)
# your form.is_valid() code start here
else:
form = FileUploadForm(request.POST, request.FILES)
# This block will only run for GET request, why using request.POST, request.FILES
return render(request, 'function/upload.html', {
'form':form
})
Here is how i got your code working
update FileUploadForm like this
class FileUploadForm(forms.ModelForm):
class Meta:
model = Document
fields = ('file_uid', 'file_name', 'file_size', 'file_document', 'uploaded_by')
# below code is only used to change the name of file_document to uploaded_file
custom_names = {'file_document': 'uploaded_file'}
def add_prefix(self, field_name):
field_name = self.custom_names.get(field_name, field_name)
return super(FileUploadForm, self).add_prefix(field_name)
use form in html like this
<form method="POST" action="" enctype="multipart/form-data">
{% csrf_token %}
{{form.file_document}}
<input type="submit" value="send"/>
</form>
Update view as
def uploadView(request):
if(request.method == 'POST'):
uploaded_file = request.FILES['uploaded_file']
file_dict = {
'file_uid' : 'test1',
'file_name' :uploaded_file.name,
'file_size' : uploaded_file.size,
'uploaded_by' : 'hemant'
}
form = FileUploadForm(file_dict, request.FILES)
if form.is_valid():
form.save()
return HttpResponse("You reached here")
else:
return HttpResponse("Your form is invalid")
else:
form = FileUploadForm()
return render(request, 'function/upload.html', {
'form':form
})

django adding multiple model image instances using form

I want to save 400 picture to my Image model using one single file field and i dont know how tp get each image from the form and create an instance on the Image model
here is my model function:
class Image(models.Model):
image = models.ImageField(null=True, blank=True)
and here is my form:
class AddImageForm(forms.ModelForm):
image = forms.FileField(widget=forms.FileInput(attrs={'class':'form-control','multiple':'true'}))
class Meta:
model = Image
fields = ['image']
and here is my view which i know is wrong just to make sure i share everything:
def imagesform(request):
form = AddImageForm()
if request.method == 'POST':
if form.is_valid():
for i in form['image']:
Image.objects.create(image=i)
context = {'form':form}
return render(request, 'members/imagesform.html', context)
Multiple file uploads can be a pain to implement, but you're almost there! From what I see, the only thing that's missing is that you should instantiate your form with the request.POST and request.FILES arguments:
def imagesform(request):
if request.method == 'POST':
form = AddImageForm(request.POST, request.FILES)
if form.is_valid():
for i in form['image']:
Image(image=i).save()
form = AddImageForm()
context = {'form':form}
return render(request, 'members/imagesform.html', context)
Also, make you sure you add the attribute enctype="multipart/form-data" to your <form> tag.

Form not registering photo Django 3.0

I'm trying to get a photo to upload and the form is not seeing the file and in the form.errors, it says 'this field is required'. I've tried using picture = request.FILES['picture'] to no avail and have also tried picture = form.FILES['picture'] as well as picture = request.POST.FILES['picture'] and picture = form.cleaned_data.get('picture') What am I missing? Let me know if you need anymore information
template
{% block content %}
<h1>Create {{post_type.title}} Post</h1>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form.as_p}}
<button type='submit'>Submit</button>
</form>
{% endblock %}
forms.py
class PicturePostForm(forms.ModelForm):
class Meta:
model = PicturePost
fields = ('description', 'privacy', 'picture', 'categories')
views.py
#login_required()
def picture_post(request):
"""
Creates new picture post
"""
if request.method == "POST":
form = PicturePostForm(request.POST)
print("is post")
if form.is_valid():
print("is valid") # this never gets printed because of the 'this field is required' error
author = request.user
content = form.cleaned_data['description']
category = form.cleaned_data['categories']
picture = form.cleaned_data['picture']
privacy = form.cleaned_data['privacy']
p_post = PicturePost(author=author, description=content, categories=category, picture=picture,privacy=privacy )
p_post.save()
#redirect to last page
return redirect('home')
else:
l = []
for i in form.errors.keys():
l.append(form.errors[i])
return HttpResponse(l)
else:
post_type = 'picture'
form = PicturePostForm()
return render(request, 'create_post.html', {'form': form, 'post_type': post_type})
The corresponding model field
picture = models.ImageField(upload_to=f'profiles/{User}_gallery', max_length=255)
Fixed it by replacing form = PicturePostForm(request.POST) with form = PicturePostForm(request.POST, request.FILES)
I have tried to complete the code before, please following
views
#login_required()
def picture_post(request):
"""
Creates new picture post
"""
form = PicturePostForm(request.POST or None, request.FILES or None)
if request.method == "POST":
if form.is_valid():
# instance new object p_post (this best practice if using forms.ModelForm)
# commit=False (to save data on ram/memory device without database/hardrive)
p_post = form.save(commit=False)
# assign author attribute from thr current user session
p_post.author = request.user
# commit=True to move/save data from memory to harddrive
p_post.save() # p_post.save(commit=True)
return redirect('home')
else:
l = []
for i in form.errors.keys():
l.append(form.errors[i])
return HttpResponse(l)
post_type = 'picture'
return render(request, 'create_post.html', {'form': form, 'post_type': post_type})

Image is not uploaded via django form

My Views
def apost(request):
if request.method =='POST':
form = APostForm(request.POST, request.FILES)
if form.is_valid():
form = form.save(commit=False)
form.slug = slugify(form.title)
form.save()
return redirect('apost')
else:
form = APostForm()
template_name = 'dadmin/form.html'
items = Post.objects.all()
context = {'title':'Add Post','form':form,'items':items}
return render (request, template_name, context)
My Form
class APostForm(forms.ModelForm):
class Meta:
model = Post
fields = {'title','photo','content'}
Models
photo = models.ImageField(upload_to='images')
No Image uploaded is Accepted Photo is selected but when Click save. It shows this field is required error. I had searched through the questions here but request.FILES solves others problems but not mines. Whats wrong?
you should use in template where you are uploading form:
<form class="form-horizontal form_middle" enctype='multipart/form-data' method="POST">
#apply logic for media upload
</form>
in views.y, the form you are saving should also have request.FILES
studentProfileForm = StudentRegisterForm(request.POST, request.FILES)
if studentProfileForm.is_valid():
user = studentProfileForm.save()
File upload is a bit weird in model forms in django.
Change your forms.py to -
class APostForm(forms.ModelForm):
photo=forms.FileField(label='Upload image') # or image field
class Meta:
model = Post
fields = {'title','content'}
form.save() will automatically save the field.

Django ModelForms: Trying to save a form with a foreign key

Django will just go to the else condition.
here's the code:
models.py
class StakeholderProfile(models.Model):
types = models.ForeignKey(Stakeholder)
name = models.CharField(blank=False, max_length=50)
forms.py
class SPForm(forms.ModelForm):
class Meta:
model = StakeholderProfile
exclude = ('key_contact_person',)
views.py
def profile(request):
stakeholderprofile = StakeholderProfile.objects.all()
if request.method == 'POST':
form = SPForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/profile/')
else:
form = SPForm()
return render_to_response('profile.html',{'form':form,'sp':stakeholderprofile})
I really need your help sir/maam.
You are excluding a field that doesn't exist in StakeHolderProfile.
Also be sure you added method='POST' in your form tag.