how do I store an image in views file in Django - django

I am making a Django website where I need to display images selected by user.
These are the things I've done:
Html form for image:
<form action="" method="POST">
{% csrf_token %}
<div class="form-group">
<label >Article Logo</label>
<input type="file" class="btn btn-primary" name="article_image">
</div>
<input type="submit" class="btn btn-success">
</form>
models.py
class Content(models.Model):
article_image = models.ImageField(upload_to = 'media', null=True)
views.py
def submit_article(request):
if request.method == 'POST':
a_image = request.FILES['article_image']
new_article.article_image = a_image
new_article.save()
I've added below code to settings.py to specify media directory:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
Added below code to urls.py of the website:
urlpatterns = [
path(r'admin/', admin.site.urls),
url(r'', include('logio.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
The form is not able to add images to the media folder. If I'm adding images through the admin panel it works.
Thanks in advance....

You need to add enctype="multipart/form-data" to your form, like this:
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
For more information, please check the documentation.
Just a suggestion, it is better to use a Django form to handle this. For example, you can have a form:
class ContentForm(forms.ModelForm):
class Meta:
model = Content
fields = ['article_image']
Then pass this form via context to template and render it:
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
<input type="submit" value="submit'>
</form>
Finally, handle validation in view:
def submit_article(request):
if request.method == 'POST':
form = ContentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
...

Related

Django upload multiple images with one input Method Not Allowed (POST): /images/

HI I have just built an HTML-form in which the user can upload multiple images but I am getting Method Not Allowed (POST): /images/ all the time. In the image_list.html the images should be shown.
Thanks for your help
models.py
class ImageModel(models.Model):
images = models.ImageField(upload_to='products/')
forms.py
class ImageForm(ModelForm):
class Meta:
model = ImageModel
fields = ['images']
widgets = {
'images': FileInput(attrs={'multiple': True}),
}
views.py
class ImageFormView(FormMixin, TemplateView):
template_name = 'image_form.html'
form_class = ImageForm
def form_valid(self, form):
# Save the images to the database
form.save()
# Redirect to the image list view
return redirect('image_list')
class ImageListView(ListView):
model = ImageModel
template_name = 'image_list.html'
context_object_name = 'images'
image_form.html
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary">Submit
</form>
image_list.html
{% load static %}
{% for image in images %}
<img src="{{image.images.url}}" alt="">
{% endfor %}
urls.py
urlpatterns = [
path('images/', views.ImageFormView.as_view(), name='image_form'),
path('', views.ImageListView.as_view(), name='image_list'),
]
You need to close button tag at HTML form
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary">Submit</button>
</form>

Uploading image is not creating media file

Guys I'm new to django I tried uploading images in the imagefield but it's not creating media folder and the database image column is also blank.
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
models.py
class Profile(models.Model):
name = models.CharField(max_length=50)
image = models.ImageField(upload_to='images/')
image.html
<form method="POST" enctype="multipart/form-data>
{% csrf_token %}
<input type="file" class="form-control" id="customFile" name="image"/></div>
<input type="text" class="form-control" name="name" placeholder="">
</div>
</form>
views.py
def hotel:
if request.method == "POST" :
post=Profile()
post.image= request.POST.get('image')
post.name = request.POST.get('name')
post.save()
return redirect('/vendor_dashboard/profile_pic')
return render(request,'profile.html')
Even tried manually creating the media file Django.
Still nothing!!
Any help Will be appreciated
Uploaded files are in request.FILES instead of request.POST. So your file handling should look like this:
# post.image= request.POST.get('image')
post.image = request.FILES['image']
I'd recommend to read the Django docs about file uploads
use request.FILES:
def hotel:
if request.method == "POST" :
post=Profile()
post.image= request.FILES['image']
post.name = request.POST.get('name')
post.save()
return redirect('/vendor_dashboard/profile_pic')
return render(request,'profile.html')
You have to include {{form.media}} to the django form template if you want to post any type of media to django
<form method="POST" enctype="multipart/form-
data>
{% csrf_token %}
{{form.media}}
<input type="file" class="form-control"
idd="customFile" name="image"/></div>
<input type="text" class="form-control"
name="name" placeholder="">
</div>
</form>
edit:
and in views.py you have to use request.FILES to get any media file(forgot to mention this)
request.FILES.get('image')
and to get the image from media use .url
{% Profileobject.image.url %}

My form for uploading photos does not work. Django

When I use the form provided by django admin everything works fine. But after creating my own form, django does not write data to my model. Is something missing in my code?
Models.py
class Offert(models.Model):
name = models.CharField(max_length=50)
file = models.FileField(upload_to='app/documents/')
forms.py
class OffertFormCV(forms.ModelForm):
class Meta:
model = Offert
fields = ( 'name',
'file')
views.py
def my_views(request):
if request.method == 'POST':
form = OffertFormCV(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('app:thank_you_page'))
else:
form = OffertFormCV()
context = {'form': form}
return render(request, 'form_application.html', context)
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('app.urls', namespace='app'))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'app/media')
form_application.html
<form method="post">
{% csrf_token %}
{{ form|crispy }}
<button type="submit" class="btn btn-primary">Send</button>
</form>
After sending the form, nothing happens. Any help will be appreciated.
You need to add enctype="multipart/form-data" to your form to be able to upload files:
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form|crispy }}
<button type="submit" class="btn btn-primary">Send</button>
</form>

Generic view UpdateView from django tutorial does not save files or images

UpdateView does not save files or images anywhere, what can be the problem?
settings:
MEDIA_ROOT=""
article_form.html:
<form method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save">
</form>
views.py:
from django.views.generic.edit import UpdateView
class updatingexample(UpdateView):
model = Article
fields = ['file1','file2','photo']
url.py
app_name = 'polls'
urlpatterns=[
path('<int:pk>/upd/', updatingexample.as_view(),name="ugh")
]
models:
class Article(models.Model):
title = models.CharField(max_length=200)
pub_date = models.DateField()
file1 = models.FileField(upload_to='uploads/',blank=True)
file2 = models.FileField(upload_to='uploads/%Y/%m/%d/',blank=True)
photo = models.ImageField(upload_to='uploads',blank=True)
def get_absolute_url(self):
return reverse('polls:ugh', kwargs={'pk': self.pk})#back to itself
Just add on your form
enctype="multipart/form-data"
So it'll end like:
<form method="post" enctype="multipart/form-data">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save">
</form>
And I also suggest that set MEDIA_ROOT and MEDIA_URL in your settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
And add it at the end of your urls.py
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

FileUpload not working in Django

I am trying to upload a file in django.
It allows me to add the file in the form and submits with no errors but nothing gets stored. I am using django-crispy-forms
models.py
class Upload(models.Model):
upload = models.FileField(upload_to='.')
views.py
class UploadsView(UpdateView):
form_class = UploadForm
template_name = 'upload.html'
model = Upload
forms.py
class UploadForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(UploadForm, self).__init__(*args, **kwargs)
class Meta:
model = Upload
fields = ('upload',)
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, '..', 'media')
MEDIA_URL = '/media/'
form.html
<form method="POST" action="">{% csrf_token %}
{{ form|crispy }}
<input class="btn btn-primary" type="submit" value="Submit" />
<button type="button" class="btn btn-danger">Cancel</button>
</form>
You need to change your form tag:
<form method="POST" action="" enctype="multipart/form-data">
From the documentation:
Note that request.FILES will only contain data if the request method was POST and the <form> that posted the request has the attribute enctype="multipart/form-data". Otherwise, request.FILES will be empty.