I'm trying to upload multiple images with one single field, in a Django application.
How to do this?
The following files are involved:
upload.html:
<form action="#" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" name="image_id" placeholder="Image Id">
<input type="file" name="file" multiple>
<button type="submit"> Upload </button>
</form>
Here, the single field image_id is meant to hold 5 images.
views.py:
def multi_image(request):
if request.method == 'POST':
img_id = request.POST.get('image_id')
file = request.FILES.getlist('file')
data_save = Res(image_id = img_id )
data_save.save()
filter_data = Res.objects.filter(image_id= img_id)
if len(filter_data) > 0:
for i in file:
print(i)
Res.objects.create(image= i)
return render(request, 'upload.html', {})
models.py:
class Res(models.Model):
image_id= models.CharField(max_length=10, blank=True, null=True)
image = models.FileField(upload_to='images', blank=True, null=True)
forms.py:
class FileForm(forms.Form):
class Meta:
model = Res
fields = '__all__'
Related
How to set image field as optional? I am trying to set image field as optional(None or selected). Image field is None its throwing "MultiValueDictKeyError" when submit the form. I want to make this image field as None.
models.py
class Profile(models.Model):
first_name = models.CharField(max_length=255, blank=True, null=True)
last_name = models.CharField(max_length=255, blank=True, null=True)
image = models.ImageField(upload_to='images', blank=True, null=True)
forms.py
class Meta:
model = Profile
fields = '__all__'
views.py
def profile(request):
if request.method == 'POST':
form = ProfileForm(request.POST)
if form.is_valid:
first_name = request.POST.get('first_name')
last_name = request.POST.get('last_name')
image = request.FILES['images']
file_storage = FileSystemStorage()
obj = Profile(first_name=first_name, last_name=last_name, image=file_storage.save(image.name, image))
return render(request, 'index.html',{})
return render(request, 'index.html',{})
return render(request, 'index.html',{})
index.html
<form action="#" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" name="first_name" class="form-control form-control" id="fname">
<input type="text" name="last_name" class="form-control form-control" id="lname">
<input type="file" name="images" class="form-control" id="image">
<button type="submit" class="btn btn-primary mt-5 mb-5">Save</button>
</form>
use the same method you're using in the other fields:
image = request.FILES.get('images')
this will make image = None if it doesn't exist in the request. then:
image_saved = None
if image is not None:
image_saved = FileSystemStorage().save(image.name, image)
obj = Profile(first_name=first_name, last_name=last_name, image=image_saved)
This is my first project in Django. I am trying to save rating in Django database but when I click on radio buttons the value doesn't store in database. I have tried solutions of Stack Overflow previously uploaded but none helped me in resolving my issue. I was firstly using RadioSelect in forms.py but still having the same problem.
Here is the code:
Model.py
class Product(models.Model):
title = models.CharField(max_length=120)
brand = models.CharField(max_length=120,default="None")
model = models.CharField(max_length=120,default="None")
slug = models.SlugField(blank=True, unique=True)
category = models.CharField(max_length=120 , default="Phone")
price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99)
class Rating(models.Model):
product=models.ForeignKey(Product,default=None, on_delete=models.PROTECT)
user=models.ForeignKey(User,default=None, on_delete=models.PROTECT)
rating = models.CharField(max_length=120)
Views.py
def add_rating(request,id):
product = get_object_or_404(Product, pk=id)
pro = Product.objects.get(id=id)
if request.method == "POST":
form = RatingForm(request.POST)
if form.is_valid():
product = form.cleaned_data['product']
user = form.cleaned_data['user']
rating = form.cleaned_data['rating']
product = request.POST.get('product', ''),
user = request.POST.get('user', ''),
rating = request.POST.get('rating', ''),
obj = Rating(product=product, user=user, rating=rating)
obj.save()
context = {'obj': obj}
return render(request, 'product/detail.html',context)
else:
form=RatingForm()
return HttpResponse('Please rate the product')
Forms.py
from django import forms
from .models import Rating
class RatingForm(forms.ModelForm):
class Meta:
model = Rating
fields = ('product', 'user','rating')
template.py
<form method="POST" action="{% url 'add_rating' product.id %}">{% csrf_token %}
<ul class="rate-area" style="display:inline;position:absolute">
<input type="radio" id="5-star" name="rating" value="5" /><label for="5- star" title="Amazing">5 stars</label>
<input type="radio" id="4-star" name="rating" value="4" /><label for="4-star" title="Good">4 stars</label>
<input type="radio" id="3-star" name="rating" value="3" /><label for="3-star" title="Average">3 stars</label>
<input type="radio" id="2-star" name="rating" value="2" /><label for="2-star" title="Not Good">2 stars</label>
<input type="radio" id="1-star" name="rating" value="1" /><label for="1-star" title="Bad">1 star</label>
<button type="submit" value="Rate">Rate</button>
</ul>
</form>
You're using a "CharField" on your model while you should be using a "ChoiceField", a ChoiceField would then become a dropdown select.
It would also be easier to use generic editing views; https://docs.djangoproject.com/en/2.2/ref/class-based-views/generic-editing/
I'm having an issue, what I need is to save a part number into a database table. So everytime a user enters the SOSS it should be save in my table. This is my code but is not saving anything, not sure what I'm doing wrong.
manifiestos.html
<form action="{% url 'manifiestos' %}" method="post"> {% csrf_token %}
<p><label for="date"> Date:</label> <input type="text" name="date" value={% now "Y-m-d" %} /> </p>
<p><label for="soss"> SOSS:</label> <input type="text" name="soss" id="soss" /> </p>
<input type="submit" value="Submit" />
</form>
models.py
class manifiestos_bts(models.Model):
soss = models.CharField(max_length=50)
date = models.DateTimeField(null=True, blank=True)
user = models.CharField(max_length=50)
forms.py
class ManifiestosForm(forms.Form):
soss = forms.CharField()
date = forms.DateTimeField()
user = forms.CharField()
html_views
#login_required(login_url='/msr/login')
def manifiestos(request):
if request.method == 'POST':
form = ManifiestosForm(request.POST)
if form.is_valid():
soss = request.POST.get('soss', '')
date = request.POST.get('date', '')
manifiestos_obj = manifiestos_bts(soss= soss, date= date)
manifiestos_obj.save()
return HttpResponseRedirect(reverse('manifiestos'))
else:
form = ManifiestosForm()
return render(request, 'manifiestos.html', {'form': form})
urls.py
url(r'^manifiestos$', html_views.manifiestos, name='manifiestos'),
Thanks for your time :)
If you need more details just let me know.
Your form.is_valid() will fail because you are not passing user from your template. Either remove it from ManifiestosForm or pass it from manifiestos.html
I can't manage to upload and save a file with a text value as a description. I don't understand why: the form and model clearly has the related fields. When I remove the reference to the text field tekst from my view, it does upload and save the file correctly. FYI: I am using a subdirectory structure basis one of the model fields, which is why there is def get_upload_to in my model and Overig_Beeld.objects.create in my view, rather than just upload.save().
Model:
def get_upload_to(instance, filename):
return 'bulkafbeeldingen/%s/%s' % (instance.bulknummer, filename)
class Overig_Beeld(models.Model):
file = models.FileField(upload_to=get_upload_to)
bestandnaam = models.CharField(max_length=256, null=True)
upload_date = models.DateTimeField(auto_now_add=True)
bulknummer = models.ForeignKey(Bulk, null=True)
tekst = models.CharField(max_length=512)
Form:
class Overig_BeeldForm(forms.ModelForm):
file = forms.FileField()
tekst = forms.CharField(required=False)
class Meta:
model = Overig_Beeld
fields = ('file', 'tekst')
template:
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<label for="file">Bestand:</label>
<input type="file" name="file"/>
<input type="text" name="tekst"/>
<input type="submit" value="Upload" />
</form>
View:
if request.method=="POST":
upload = Overig_BeeldForm(request.POST, request.FILES)
if upload.is_valid():
f = request.FILES['file']
Overig_Beeld.objects.create(file=f, bestandnaam=f.name, bulknummer=bulk, tekst=upload.tekst )
return redirect(reverse('bulk', args=(bulk.slug,)))
error:
'Overig_BeeldForm' object has no attribute 'tekst'
Uploaded data contains in cleaned_data attribute in django form's instance. So
text = upload.cleaned_data['tekst']
will fix your problem
New to Django and Python and I need a little help with a foreign key drop down. Basically, I have a category model and a image model and I want users to be able to choose which category to put the image in. How do I create a drop down for the category in the image form? Are my views and html correct too? I have had a look online but I can't seem to do it myself. I keep getting errors.
Here are my models:
class Images(models.Model):
image = models.ImageField(upload_to='images', blank=False)
img_name = models.CharField(max_length=120, blank=True)
img_date = models.DateTimeField(default=now())
img_user = models.ForeignKey(User)
img_cat_id = models.ForeignKey(Categories)
def __unicode__(self):
return self.img_name
class Categories(models.Model):
cat_descr = models.CharField(max_length =120, blank=False)
def __unicode__(self):
return self.cat_descr
VIEWS:
#login_required
def upload_images(request):
context = RequestContext(request)
context_dict={}
if request.method == 'POST': # render the form, and throw it back.
# take the form data and process it!
form = UploadImagesForm(request.POST, request.FILES)
if form.is_valid():
print 'form is_valid'
upload_image = form.save(commit=False)
upload_image.img_user = request.user
if 'image' in request.FILES:
upload_image.image =request.FILES['image']
upload_image.save()
return render(request, 'rmb/upload.html', {'upload_image': form})
else:
print form.errors
# Not a HTTP POST, so we render our form using two ModelForm instances.
# These forms will be blank, ready for user input.
else:
form = UploadImagesForm()
context_dict = {'upload_image': form}
all_categories = Categories.objects.order_by('-id')
context_dict['all_categories'] = all_categories
print context_dict
return render_to_response('rmb/upload.html', context_dict, context)
FORMS:
class UploadImagesForm(forms.ModelForm):
#cat_list = ModelChoiceField(queryset=Categories.objects.all())
class Meta:
model = Images
fields=('image','img_name')
HTML:
{% block body_block %}
<form id="upload_form" method="post" action="/rmb/upload/"
enctype="multipart/form-data">
{% csrf_token %}
{{ upload_image.as_table }}
<input type="submit" name="submit" value="Upload" />
{% for categories in all_categories %}
<div> {{ categories.id }} </div>
{{ categories.cat_descr }}
<input type="submit" name="submit" value="Upload" />
{% endfor %}
</form>
{% endblock %}
You don't need to insert the HTML for the form manually, just use {{form}} in the template.
{% block body_block %}
<form id="upload_form" method="post" action="/rmb/upload/"
enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
</form>
{% endblock %}
By default a ForeignKey will be a select field so you shouldn't need to do much else.
As an aside, give your models and fields more appropriate names. We know these are all image fields, because they are on the image and make sure, unless your model is a collection of things, you give it a singular name. Lastly, when using a Foreign Key and item gets an extra field of fieldname_id that is just the ID, whereas fieldname is the property that gives the related item as well.
So instead of:
class Images(models.Model):
image = models.ImageField(upload_to='images', blank=False)
img_name = models.CharField(max_length=120, blank=True)
img_date = models.DateTimeField(default=now())
img_user = models.ForeignKey(User)
img_cat_id = models.ForeignKey(Categories)
Use:
class Image(models.Model):
image = models.ImageField(upload_to='images', blank=False)
name = models.CharField(max_length=120, blank=True)
date = models.DateTimeField(default=now())
user = models.ForeignKey(User)
category = models.ForeignKey(Categories)