How to upload a folder to django database through form - django

I want to upload a folder containing few files, and save those files to the database. I was successful in uploading a file, but facing problem while trying to upload a folder. The files does not get stored in the database. Can someone please tell me where am I going wrong.
models.py
class Document(models.Model):
report_id = models.CharField(max_length=50, blank=False)
description = models.CharField(max_length=255, blank=False)
document = models.FileField(upload_to='documents/')
uploaded_at = models.DateTimeField(auto_now_add=True)
is_diagnoised = models.BooleanField(default=False)
uploaded_by_doc = models.CharField(max_length=20, default="")
downloaded_by_rad = models.CharField(max_length=20, default="")
forms.py
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = ('report_id', 'description', )
views.py
def index(request):
if request.user.is_authenticated:
uid = request.user.id
usern = request.user.username
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
for afile in request.FILES.getlist('document'):
new_file = Document(document = afile)
post = form.save(commit=False)
post.uploaded_by_doc = usern
post.document = form.cleaned_data.get('new_file')
post.save()
return HttpResponseRedirect('index')
else:
form = DocumentForm()
return render(request, 'upload.html', context)
upload.html
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="file" name="document" multiple = "true" webkitdirectory="true" directory = "true"/>
<button type="submit">Upload</button>

Related

Django upload image using page slud/id

I'm trying to add the ability to upload an image to a post but having issues.
The image field is in its own model but uses a foreign key to show which post it relates to.
At the moment the upload button does not post the form but also how would I use the post page url/slug/id as the image foreign key.
Would i need to call it in the html post page?
views.py
def designUpload(request):
if request.method == 'POST':
form = ImageForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return render(request, 'users/dashboard.html')
else:
form = ImageForm()
return render(request, 'users/dashboard.html', {
'form': form
})
**models.py**
class Designs(models.Model):
forbrief = models.ForeignKey(Brief, on_delete=CASCADE)
postedby = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
design = models.ImageField(null=True, blank=True)
date = models.DateTimeField(auto_now=True, blank=True)
forms.py
class ImageForm(forms.ModelForm):
class Meta:
model = Designs
fields = ["design",]
HTML Form
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="image" name="mydesign">
<button type="submit">Upload</button>
</form>

Django MultiValueDictKeyError for upload file

There has a file upload page for upload file to a object by id in model. However, it shown MultiValueDictKeyError after submitted. I would appreciate if any help.
models.py:
class Order(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True)
items = models.ManyToManyField(OrderItem)
img_upload = models.FileField(upload_to='payment', null=True)
forms.py:
class Upload_File(forms.Form):
class Meta:
model = Order
fields = ('img_upload')
views.py:
def upload_page(request, id):
order = get_object_or_404(Order, id=id)
form = Upload_File(request.POST or None, request.FILES or None)
if request.method == 'POST':
order.img_upload = request.FILES['file']
if form.is_valid():
form.save()
messages.success(request, 'Succeed')
return redirect('user_info')
else:
form = Upload_File()
context = {
'form': form,
}
return render(request, 'upload.html', context)
html:
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input class="form-group" type="file" name="file">
<button class="form-group" type="submit">Submit</button>
</form>

Django is rendering empty template to create new profile instead of submitting form

First some code:
models.py
class Findings(models.Model):
patient = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.CASCADE)
finding_type = models.CharField(max_length=35, null=True)
upload = models.FileField(null=True, blank=True)
date_created = models.DateField(auto_now=True)
description = models.TextField(null=True, blank=True)
def __str__(self):
return self.finding_type
forms.py
class AddFindingForm(ModelForm):
class Meta:
model = Findings
fields = ('finding_type', 'description', 'upload', 'patient')
labels = {
'finding_type' : _('Rodzaj badania'),
'description': _('Opis'),
'upload': _('Dodaj plik'),
}
views.py
def add_finding(request):
form = AddFindingForm()
if request.method == 'POST':
form = UserProfileForm(request.POST, request.FILES)
if form.is_valid():
form = form.save(commit=False)
form.patient = request.user.profile
form.save()
return redirect('profile')
context = {'form': form}
return render(request, 'add_finding.html', context)
template
{% block content %}
<form method="POST" enctype="multipart/form-data" action="">
{% csrf_token %}
{{ form.as_p}}
<button type="submit"> Wyƛlij </button>
</form>
{% endblock %}
So, everytime i'm trying to submit a filled form it displays another form to create new Profile, even if i'm setting patient manually.
The empty form it's displaying is on the same url.
I have no idea why it's doing that...
You are submitting your request.POST data to wrong form. Doing this user's submitted data never gets into AddFindingForm() instead it should be,
def add_finding(request):
form = AddFindingForm()
if request.method == 'POST':
form = AddFindingForm(request.POST, request.FILES) # Change Here
if form.is_valid():
form = form.save(commit=False)
form.patient = request.user.profile
form.save()
return redirect('profile')
context = {'form': form}
return render(request, 'add_finding.html', context)

Django] Saving multiple images by formset doesn't work

I'm trying to save multiple Images and his parent's data together on the same template.
I have one parent's model(to save normal data) and child's model(to save images). In this case, saving parent's data is working very well. but images are not work.
There isn't any error message.
//model
class QuotationPanchok(models.Model):
whose = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=50, help_text='', default='')
many = models.IntegerField(default='1', help_text='')
design = models.CharField(max_length=3, choices=(('yes', 'yes'), ('no', 'no'),))
sian = models.CharField(max_length=3, choices=(('yes','yes'), ('no', 'no'),))
havefile = models.CharField(max_length=3, choices=(('yes','yes'), ('no', 'no'),))
deadline = models.DateField(blank=True)
addressto = models.CharField(max_length=50, default='', help_text='')
fulltext = models.TextField(max_length=150, blank=True)
status = models.CharField(max_length=7, choices=(('not','not'), ('finish', 'finish'),), default='not')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
class ImagesForQuotation(models.Model):
whose = models.ForeignKey(QuotationPanchok, on_delete=models.CASCADE)
image = models.ImageField(upload_to='images/', blank=True, null=True)
def __str__(self):
return self.whose.title + " Image"
// views
def quotation_create(request):
ImageFormset = modelformset_factory(ImagesForQuotation, fields=('image',), extra=4)
if request.method == 'POST':
form = QuotationCreateForm(request.POST)
formset = ImageFormset(request.POST or None, request.FILES or None)
if form.is_valid() and formset.is_valid():
post = form.save(commit=False)
post.whose = request.user
post.save()
for f in formset:
try:
photo = ImagesForQuotation(whose=post, image=f.cleaned_date['image'])
photo.save()
except Exception as e:
break
return redirect('index')
else:
form = QuotationCreateForm()
formset = ImageFormset(queryset=ImagesForQuotation.objects.none())
context = {
'form': form,
'formset': formset,
}
return render(request, 'quotationapp/quotation_create.html', context)
//forms
class QuotationCreateForm(forms.ModelForm):
class Meta:
model = QuotationPanchok
fields = (
'title',
'many',
'design',
'sian',
'havefile',
'deadline',
'addressto',
'fulltext',
)
def __init__(self, *args, **kwargs):
super(QuotationCreateForm, self).__init__(*args, **kwargs)
for field_name, field in self.fields.items():
field.widget.attrs['class'] = 'form-control'
//template(quotation_create.html)
{% block content %}
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
{{ formset.as_table }}
<input type="submit" class="btn btn-primary" value="">
</form>
{% endblock %}
How can I solve this problem?
Thank you..

Problem saving data in a modelform

I have a modelform set up for a user to enter his contact info. The validation and form.is_valid() method is working, however the request.POST data is not being stored to the db, and I'm having trouble figuring out what the problem is. Here is what I currently have --
# model
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
contact_email = models.EmailField(max_length=100, blank=True)
contact_phone = models.IntegerField(max_length=11, blank=True)
website = models.CharField(max_length=256, blank=True)
class ContactInfoForm(ModelForm):
class Meta:
model = UserProfile
fields = ('contact_email', 'contact_phone', 'website',)
# view
#login_required
def edit_contact(request):
contact_email = request.user.get_profile().contact_email
form = ContactInfoForm(initial={'contact_email':contact_email,})
if request.method == 'POST':
form = ContactInfoForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
return render_to_response(...)
# template
<form action="." method="post"> {% csrf_token %}
<table>
{{form}}
</table>
<p><input type="submit" name="save_changes" value="Save Changes" ></p>
</form>
I think the error might be the instance you're calling in your ModelForm. You need to use a UserProfile instance, but you're using a User instance. The following might work (untested):
#login_required
def edit_contact(request):
contact_email = request.user.get_profile().contact_email
form = ContactInfoForm(initial={'contact_email':contact_email,})
user_profile = UserProfile.objects.get(contact_email=contact_email)
if request.method == 'POST':
form = ContactInfoForm(request.POST, instance=user_profile)
if form.is_valid():
form.save()
return render_to_response(...)