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 %}
Related
I am using Djnago.i Have html Form such as below,
<form method="POST" action="{% url 'someaction' %}" enctype="multipart/form-data">
<input type="file" name="image" id="image">
</form>
How to check request.FILES['image'] is Selected or not in djnago view file?
Do:
image = request.FILES.get('image')
if image is None:
# request.FILES['image'] is not posted
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()
...
When I upload the image from admin panel it goes to http://127.0.0.1:8000/media/shop/images/Digital_India_empower_youth.jpg but when I upload from web page it shows uploaded with name in admin panel and no directory displayed and does not show in directory of project
models.py
class Product(models.Model):
product_id = models.AutoField
product_name = models.CharField(max_length=50)
category = models.CharField(max_length=50,default="")
price = models.IntegerField(default=0)
desc = models.CharField(max_length=300,default="")
image = models.ImageField(upload_to='shop/images', default="")
#chk=True
def __str__(self):
return self.product_name
views.py
def product(request):
if request.method=="POST":
name=request.POST.get('name','')
category=request.POST.get('category','')
price=request.POST.get('price','')
desc=request.POST.get('desc','')
image=request.POST.get('image','')
product=Product(product_name=name,category=category,price=price,desc=desc,image=image)
product.save()
return render(request, 'shop/sell.html')
setting.py
STATIC_URL = '/static/'
MEDIA_ROOT=os.path.join(BASE_DIR,'media')
MEDIA_URL='/media/'
sell.html
<div class="form-group">
<label for="price">Price</label>
<input type="text" class="form-control" id="price"
name="price"placeholder="100">
</div>
<div class="form-group">
<label for="desc">Description</label>
<input type="text" class="form-control" id="desc"
name="desc" placeholder="Write few things about books">
</div>
<div class="form-group">
<label for="image">Upload Image</label>
<input type="file"id="image" name="image">
</div>
<button type="submit" class="btn btn-primary">Sell</button>
</div>
I'm not sure how you're settings file look but you need to setup MEDIA_URL and MEDIA_ROOT
There is a couple of way's you can do this, you can use Django FileSystemStorage or use ModelForms and save it over model.
Django have the complete example on how to do this read the FileUplods section.
In the end for the HTML you need to set and this is mandatory enctype="multipart/form-data" or the request.FILES will be empty.
The error was that i was not using file storage and only name of file save in image field so use the described format which is described below
views.py
if request.method=="POST" and request.FILES['imag']:
image=request.FILES['imag']
fs=FileSystemStorage()
fs.save(image.name,image)
image=image
name=request.POST.get('name','')
category=request.POST.get('category','')
price=request.POST.get('price','')
desc=request.POST.get('desc','')
product=
Product(product_name=name,category=category,
price=price,desc=desc,image=image)
product.save()
sel=True
#chk=True
return render(request,'shop/product.html')
I am trying to edit an html page so a logged in user can favorite / bookmark a video.id
Here is the .html file
<td>
<form method='POST' action="{% url 'researcher_view_app:favourite_post' video.id %}">
{% csrf_token %}
<input type='hidden' name='video' value={{ video.id }}>
<button type='submit'>Bookmark</button>
</form>
</td>
Here is the urls.py file
path('<int:fav_id>/favourite_post', views.favourite_post, name='favourite_post'),
Here is the view.py file
def favourite_post(request, fav_id):
video = get_object_or_404(Video, id=fav_id)
if request.method == 'POST':
video.
return render(request, 'researcher_view_app/%s' % fav_id)
First you modify the models.py that has the user models
class ProjectUser(AbstractUser):
images = models.ManyToManyField(Images)
def __str__(self):
return self.email
In the .html file add the following:
{% for image in available_images %}
/* show image */
<form method='post' action="{% url 'user-image-add' %}">
{% csrf_token %}
<input type='hidden' name='image' value={{image.id}}>
<button type='submit'>bookmark</button>
</form>
{% endfor %}
In your views.py add the following method
def user_image_add(request):
user_image_form = ImageForm(request.POST or None)
if request.method == 'POST' and user_image_form.is_valid():
request.user.images.add(user_image_form.cleaned_data['image'])
return JsonResponse(status=200)
raise Http404()
Create a forms.py file in your add and add the following:
class ImageForm(forms.Form):
image = forms.ModelChoiceField(queryset=Images.objects.all())
To show those bookmarked images you can just iterate over request.user.images (it gives you a QS of Images) similar to code above.
In the urls.py add the following:
path('user-image-add/', views.user_image_add, 'user-image-add')
In models.py add a method in User model for getting bool if video is bookmarked
def is_bookmarked(self, video_id):
return self.bookmarked_videos.filter(id=video_id).exists()
simirlarly is_bookmarked can be added to Video model accepting user_id and checking video.projectuser_set.
And add the following to your .html file where users bookmarked a video
`{% if video.is_bookmarked %}`
Delete the UserProfile as you do not need it. Just make sure to have needed instance in context of view.
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.