Upload multiple files with one single input - django

Multiple files do not save in admin, only the first saved in admin.
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/')
image_caption = models.CharField(max_length=700)
def upload(request):
form = PostForm(request.POST,request.FILES)
if request.method == "POST":
if form.is_valid():
for f in request.FILES.getlist('image'):
post = Image(image=f)
post = form.save(commit=False)
post.imageuploader_profile = request.user
print(request.user)
post.save()
form.save()
return redirect('/')
else:
form = PostForm()
return render(request, 'upload.html', {"form": form})
class PostForm(forms.ModelForm):
class Meta:
model = Image
fields = ('image_caption', 'image',)
<form action="{% url 'site:upload' %}" method="post" enctype="multipart/form-data">
{%csrf_token%}
<input type="file" name="file" multiple onchange="loadFile(event)" required="" id="id_file">
<button type="submit">Post</button>
</form>

It looks like your form is for an Image object, but you're trying to create multiple images from a single form submit.
You are creating the Image(), but it doesn't look like you're attaching it to the form. So you'll probably need to reorganize the view something like:
def upload(request):
if request.method == "POST":
for image_file in request.FILES.getlist('image'):
form = PostForm(request.POST, image_file)
if form.is_valid():
image = form.save(commit=False)
image.imageuploader_profile = request.user
image.save()
form.save()
return redirect('/')
else:
form = PostForm()
return render(request, 'upload.html', {"form": form})
Also, cut/paste can mess up formatting, but always double-check your indentation for intended flow.

use this code:-----------------------------
def upload(request):
form = PostForm(request.POST,request.FILES)
if request.method == "POST":
if form.is_valid():
for f in request.FILES.getlist('file'):
post = Image(image=f)
post = form.save(commit=False)
post.imageuploader_profile = request.user
print(request.user)
post.save()
form.save()
return redirect('/')
else:
form = PostForm()
return render(request, 'upload.html', {"form": form})
class PostForm(forms.ModelForm):
class Meta:
model = Image
fields = ('image_caption', 'image',)
<form action="{% url 'site:upload' %}" method="post" enctype="multipart/form-data">
{%csrf_token%}
<input type="file" name="file" multiple onchange="loadFile(event)" required="" id="id_file">
<button type="submit">Post</button>
</form>

Related

How to stop Django from rendering result in new tab

I have following views and each time form is submitted, result is rendered in new tab which has empty form.
How to render result in same form (with data submitted) without opening new tab?
views.py
class contact(View):
def __init__(self, logger=None, **kwargs):
self.logger = logging.getLogger(__name__)
def get(self, request):
return render(request, 'test.html')
def post(self, request):
if request.method == 'POST':
form = ContactForm(request.POST, request.FILES)
if form.is_valid():
self.host = form.data['ip']
messages.success(request, "Successful")
else:
form = ContactForm()
else:
form = ContactForm()
return render(request, 'test.html', {'form':form})
forms.py
class ContactForm(forms.Form):
ip = forms.CharField()
urls.py
urlpatterns = [
path('', contact.as_view()),
]
html
<body>
<form action="/" method= "post" enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
<button type="submit">Submit</button>
</form>
</body>
if form.is_valid()
form.save()
messages.success(request, 'Contact request submitted successfully.')
return render(request, 'your_page.html', {'form': ContactForm(request.GET)})

django model based forms - why isn't form valid?

I'm trying to make model based form but something went wrong.
model:
class Topic(models.Model):
name = models.CharField(max_length=200)
icon = models.ImageField(upload_to = 'images/')
form:
class TopicCreationForm(ModelForm):
class Meta:
model = Topic
fields = '__all__'
view:
def TopicCreateView(request):
form = TopicCreationForm()
if request.method == 'POST':
form = TopicCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
else:
print('aaa') # It displays in console
context = {'form':form}
return render(request, 'blog/topic_form.html', context)
my form html part
<form method="POST">
{% csrf_token %}
<fieldset >
<legend> New Topic</legend>
{{ form|crispy }}
</fieldset>
<div>
<input type="submit" value="submit" class="button-33" role="button">
</div>
</form>
where did i make mistake ?
You need to pass both request.POST and request.FILES [Django-doc], so:
def topic_create(request):
if request.method == 'POST':
form = TopicCreationForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('home')
else:
print('aaa') # It display in console
else:
form = TopicCreationForm()
context = {'form':form}
return render(request, 'blog/topic_form.html', context)
In the HTML form, you need to specify that the files should be encoded with the enctype="…" attribute [mdn]:
<form method="post" enctype="multipart/form-data">
…
</form>

Django I need upload file button only remove choose file and don't need refresh page when upload

I want to upload only button and don't need refresh when upload how to fix this
model_form_upload.html
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" >Upload</button>
</form>
forms.py
class DocumentForm(forms.ModelForm):
class Meta:
model = DocumentFile
fields = ['document']
views.py
def model_form_upload(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('home')
else:
form = DocumentForm()
print(form)
return render(request, 'model_form_upload.html', {'form': form})

MultipleObjectsReturned display when form is submitted

i have a model with FileField, when i submit a form uploading images it submits for the first time. But when i want to upload another image i get this error: get() returned more than one Image -- it returned 2!
class Image(models.Model):
imageuploader_profile = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True, blank=True)
first_upload_image = models.FileField(upload_to ='pictsagram/',null=True)
second_upload_image = models.FileField(upload_to ='pictsagram/',null=True)
def home(request):
all_images = Image.objects.filter(imageuploader_profile=request.user.id)
try:
upload_images = Image.objects.get(imageuploader_profile=request.user.id)
except Image.DoesNotExist:
upload_images = None
all_users = Profile.objects.all()
next = request.GET.get('next')
if next: return redirect(next)
context = {
'all_images': all_images,
'all_users': all_users,
'upload_images': upload_images,
}
return render(request,'home.html', context,)
def upload(request):
form = PostForm(request.POST,request.FILES)
if request.method == "POST":
print(request.FILES)
if form.is_valid():
post = form.save(commit=False)
post.imageuploader_profile = request.user
post.save()
return redirect('/')
else:
form = PostForm()
return render(request, 'upload.html', {"form": form})
{% if upload_images.first_upload_image %}
<img src="{{ upload_images.first_upload_image.url }}" class="img-fluid d-block w-100" alt="orange tree" />
{% endif %}
{% if upload_images.second_upload_image %}
<img src="{{ upload_images.second_upload_image.url }}" class="img-fluid d-block w-100" alt="orange tree" />
{% endif %}
If you use modelname.objects.get("field_name"="**")
It will always give you a single object that matches your query.
If your database contains more than one objects that matches your query you should use filter
modelname.objects.filter("field_name"="**")
This happens because every time when you submit the form you write a new record in the database instead of updating the current one.
Assuming that imageuploader_profile can only have one row in the table
def upload(request):
upload_images = Image.objects.filter(imageuploader_profile=request.user.id).first()
form = PostForm(instance=upload_images)
if request.method == "POST":
form = PostForm(request.POST, request.FILES, instance=upload_images)
if form.is_valid():
post = form.save(commit=False)
post.imageuploader_profile = request.user
post.save()
return redirect('/')
return render(request, 'upload.html', {"form": form})

Django ModelForm does not save to database

I try to add a comment but it does not save it to the database. There is no error.
My Views is
def add_comment(request, id):
article = get_object_or_404(Article, id=id)
if request.method == "POST":
form = CommentForm(request.POST,instance=article)
if form.is_valid():
comment = form.save(commit=False)
comment.post = article
comment.save()
return redirect('articles:detail', pk=article.pk)
else:
form = CommentForm()
template="article/comment.html"
return render(request, template, {'form': form})
comment.html:
<form method="POST">{% csrf_token %}
{{form.as_p}}
<button type="submit">Send</button>
forms.py
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('name', 'comment')