I have the following view which allows me to save the information of a multi step application.
def saveNewApplication(request, *args, **kwargs):
educationList = [ val for val in pickle.loads(bytes.fromhex(request.session['education'])).values() ]
basicInfoDict = pickle.loads(bytes.fromhex(request.session['basic_info']))
documentsDict = pickle.loads(bytes.fromhex(request.session['documents']))
applicant, created = ApplicantInfo.objects.update_or_create(
applicantId=request.session['applicantId'],
defaults={**basicInfoDict}
)
if created:
#saving the diplomas
for education in educationList:
Education.objects.create(applicant=applicant, **education)
with open(f"{documentsDict['cv_url']}/{request.session['file_name']}", 'rb') as f:
Documents.objects.create(
applicant=applicant,
cv =File(f, name=os.path.basename(f.name)),
langue_de_travail = documentsDict['langue_de_travail']
)
#remove the temporary folder
shutil.rmtree(f"{documentsDict['cv_url']}")
else:
educationFilter = Education.objects.filter(applicant=applicant.id)
for idx, edu in enumerate(educationFilter):
Education.objects.filter(pk=edu.pk).update(**educationList[idx])
#updating the documents
document = get_object_or_404(Documents, applicant=applicant.id)
if documentsDict['cv_url']:
with open(f"{documentsDict['cv_url']}/{request.session['file_name']}", 'rb') as f:
document.cv = File(f, name=os.path.basename(f.name))
document.save()
document.langue_de_travail = documentsDict['langue_de_travail']
document.save()
languagesDict = pickle.loads(bytes.fromhex(request.session['languages']))
Languages.objects.update_or_create(applicant=applicant, defaults={**languagesDict})
if 'experiences' in request.session and request.session['experiences']:
experiencesList = [ pickle.loads(bytes.fromhex(val)) for val in request.session['experiences'].values() ]
Experience.objects.filter(applicant=applicant.id).delete()
for experience in experiencesList:
Experience.objects.create(applicant=applicant, **experience)
return JsonResponse({'success': True})
In the development it works perfectly but if deployed I am getting a 404 raise by this line get_object_or_404(Documents, applicant=applicant.id) meaning the creating is false. and I can't figure why is that.
The weirdest thing is if I do comment the entire else block it also returns a 500 error but this time it I do click in the link of the console it show the right response not redirected {success:true}
down below is my javascript fonction for handling the view.
applyBtn.addEventListener("click", () => {
var finalUrl = "/api/applications/save-application/";
fetch(finalUrl)
.then(res => res.json())
.then(data => {
if (data.success) {
window.location.href = '/management/dashboard/';
} else {
alert("something went wrong, Please try later");
}
})
});
I am using postgresql as a database I deleted twice but nothing.
the url file is here.
path("api/applications/save-application/", views.saveNewApplication, name="save-new-application"),
path("api/applications/delete-applicant/<slug:applicantId>/", views.deleteApplicant , name="delete-applicant"),
path('api/edit-personal-info/', editPersonalInfo, name="edit-personal-info"),
Any help or explanation would be highly appreciated. Thanks in advance.
Related
I'm having very stupid problem: I can't get to filter data I'm getting from django rest by any means. Using /?something=value does not thin out the results obtained, I'm still getting all the results. I tried using param, but it basically does same thing and is still not working. I don't know if I'm missing something, but even when I go to views of my database it is not working.
async created() {
try {
const response = await
axios.get("http://127.0.0.1:8000/api/comments/?article=" + this.id);
let tmp = response.data
this.comments = tmp
this.error = ''
} catch(err) {
this.error=err
}
}
this is how it looks in django rest view
I really enjoy the filepond library and would like to implement it in my flask app. Since I was not able to find any useful examples online, I started to write my own, small, proof of concept web application. I would like to upload multiple images to the server and save the filenames in the database. Furthermore, I would like to edit an entry and add additional files or remove the existing ones.
So far I figured out how to upload and revert files before the form is submitted. I am also able to load existing files inside the edit form. Just when I click the 'x' button on a loaded image inside the edit form the image is removed from the filepond window and a 'removefile' event is fired, but the file still remains on the server. Is it possible to trigger the revert request on a loaded file or is there a better solution altogether?
x-button does not remove the file from the server
Here are the relevant snippets from my js file:
FilePond.registerPlugin(
FilePondPluginFileValidateSize,
FilePondPluginImagePreview,
FilePondPluginFileRename,
FilePondPluginFileValidateType
);
inputElement = document.querySelector(".filepond");
token = document
.querySelector('input[name="csrf_token"]')
.getAttribute("value");
FilePond.setOptions({
server: {
headers: { "X-CSRF-TOKEN": token },
process: "./process",
revert: "./revert",
load: {
url: "../",
}
},
});
const filepond = FilePond.create(inputElement, {
// Here I pass the files to my edit form in the following format:
//
// files: [
// {
// source: 'static/images/some_name.png',
// options: {
// type: 'local'
// }
// }]
});
The relevant code from .py file:
#app.route("/process", methods=["POST"])
#app.route("/edit/process", methods=["POST"])
def process():
upload_dir = "static/images"
file_names = []
for key in request.files:
file = request.files[key]
picture_fn = file.filename
file_names.append(picture_fn)
picture_path = os.path.join(upload_dir, picture_fn)
try:
file.save(picture_path)
except:
print("save fail: " + picture_path)
return json.dumps({"filename": [f for f in file_names]})
#app.route("/revert", methods=["DELETE"])
#app.route("/edit/revert", methods=["DELETE"])
def revert():
upload_dir = "static/images"
parsed = json.loads(request.data)
picture_fn = parsed["filename"][0]
picture_path = os.path.join(upload_dir, picture_fn)
try:
os.remove(picture_path)
except:
print("delete fail: " + picture_path)
return json.dumps({"filename": picture_fn})
Here is the repository to my full flask-filepond app:
https://github.com/AugeJevgenij/flask_filepond
Please excuse me if the question is unclear, does not make sense or the code is written poorly.
I just started programming a few months ago.
Acording to filepond documentation you can remove a file stored locally on the server like this:
FilePond.setOptions({
server: {
remove: (source, load, error) {
// 'source' is the path of the file and should be sent to a server endpoint via http
// call the load method before ending the function
load()
}
}
})
then on your server where you receive the source (path), use it to delete the file. Keep in mind that this is a risky approach to get your website hacked!
I'm using Unity 2018.3. and try to HTTP POST Request with image from Unity to Django.
try to take a picture in Unity and then POST the image to Django server.
I want to receive in server and make it to image file.
well, when i send for image file to byte[] using EncodeToPNG() or EncodeToJPG(), the server got it but when i print it the data it was crash seems like encoding error. so it can't write to image format. (the take a picture code is working right.)
Django server result image
i saw a bunch of things about this issue so i tried to other way like use WWWform or JSON but anything couldn't works..
how to get image form Unity to Django?
All help appreciated! Thanks, all.
take a picture
void TakeSnapshot()
{
Texture2D snap = new Texture2D(frontCam.width, frontCam.height);
snap.SetPixels(frontCam.GetPixels());
snap.Apply();
_SavePath = pathForDocumentsFile("photo");
System.IO.File.WriteAllBytes(_SavePath + ".png", snap.EncodeToPNG());
bytes = snap.EncodeToPNG();
//bytes = snap.EncodeToJPG();
UnityEngine.Object.Destroy(snap);
path = _SavePath + ".png";
StartCoroutine(ServerThrows());
}
POST to server
IEnumerator ServerThrows()
{
List<IMultipartFormSection> formData = new List<IMultipartFormSection>();
formData.Add(new MultipartFormDataSection("photo", bytes, "byte[]"));
//UnityWebRequest www = UnityWebRequest.Post(url, null, bytes);
UnityWebRequest www = UnityWebRequest.Post(url, formData);
www.chunkedTransfer = false;
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
Debug.Log("Form upload complete!" + www.downloadHandler.text);
}
}
response in server
def post(self, request, format=None):
print('get the data')
print('request.POST: ', request.POST)
print('request.headers: ', request.headers)
data_test = request.POST.get('photo', '')
print('data test is : ', data_test)
print('type of data_test is : ', type(data_test))
print('length of data_test is : ', len(data_test))
print('finish to get ')
# data_test = data_test.decode('utf-8').encode('euc_kr','replace')
f = open('./test.png','wb')
f.write(data_test.encode())
f.close()
#
data = open('./test.png', 'rb')
return HttpResponse("post !")
I'm trying to save pdf on server using rails model buts its generate a blank pdf. Earlier did it in controller without problem but now its creating a blank one. Any idea What's i did wrong?
def generate_bulk_pdf
view = ActionView::Base.new(ActionController::Base.view_paths, {})
view.extend(ApplicationHelper)
view.extend(AbstractController::Rendering)
view.extend(Rails.application.routes.url_helpers)
students = Student.all.order('id ASC')
students.each do | aStudent |
pdf = WickedPdf.new.pdf_from_string(
view.render_to_string(
:template => "#{Rails.root.join('templates/challen.pdf.erb')}",
:locals => { '#student' => aStudent }
)
)
save_path = Rails.root.join('pdfs','filename.pdf')
File.open(save_path, 'wb') do |file|
file << pdf
end
end
end
Any idea What's i did wrong? I can't find any solution
A good test is just put a simple line of text in your template and see if you get a PDF with that line. Strip everything back so you just generating a PDF with no coming locals, just that 1 string and let me know.
Here is how I set up mine and it works fine, it might click something :)
def generate_pdf_voucher(voucher, dir_name)
view = ActionView::Base.new(Rails.root.join('app/views'))
view.class.include ApplicationHelper
view.class.include Rails.application.routes.url_helpers
pdf = view.render :pdf => a_name,
:template => 'layouts/pdfs/voucher_pdf',
:layout => 'layouts/pdfs/pdf.html.erb',
:header => {:right => '[page] of [topage]'},
:locals => {:#voucher => voucher}
# then save to a file
pdf = WickedPdf.new.pdf_from_string(pdf)
save_path = Rails.root.join('public', 'pdfs', dir_name, "#{voucher[:user].id.to_s}.pdf")
File.open(save_path, 'wb') do |file|
file << pdf
end
end
pdf.html.erb is the structure of the PDF
voucher_pdf is all the dynamic stuff
If this wasn't helpful, then put a comment on and I will delete it.
I'm working on a view in my Django 1.5 that allow me to download a file. The download process it's triggered by a button in the HTML page like this:
<input type="button" value="Download!" />
The url point to a view that manage the download:
def filedownload(request, filename):
down_file = File.objects.get(name = filename)
file_path = MEDIA_ROOT+str(down_file.file)
file_name = down_file.filecomplete()
if not Transaction.objects.filter(user = request.user, file = down_file):
transaction = Transaction.objects.create(date = datetime.now(), user = request.user, file = down_file, vote = False)
transaction.save()
fp = open(file_path, 'rb')
response = HttpResponse(fp.read())
fp.close()
type, encoding = mimetypes.guess_type(file_name)
if type is None:
type = 'application/octet-stream'
response['Content-Type'] = type
response['Content-Length'] = str(os.stat(file_path).st_size)
if encoding is not None:
response['Content-Encoding'] = encoding
if u'WebKit' in request.META['HTTP_USER_AGENT']:
filename_header = 'filename=%s' % file_name.encode('utf-8')
elif u'MSIE' in request.META['HTTP_USER_AGENT']:
filename_header = ''
else:
filename_header = 'filename*=UTF-8\'\'%s' % urllib.quote(file_name.encode('utf-8'))
response['Content-Disposition'] = 'attachment; ' + filename_header
return response
What I wanted to do it's to redirect the user to a success page right after they hit the downlad button but I can't find a way to do it.
I'm not concerned about interrupted or otherwise unsuccessful downloads since it's a school project.
He are all steps that you have to follow to run your code :
get the jQuery File Download which allows downloads with OnSuccess and OnFailure callbacks.
Here is a simple use case demo using the plugin source with promises. The demo page includes many other, 'better UX' examples as well.
$.fileDownload('some/file.pdf')
.done(function () { //redirect });
Here is a simple use case demo using the plugin source with promises. The demo page includes many other, 'better UX' examples as well.
You could set the href for the input to the download confirmation page you want to display, passing along the file name, then within the template for the confirmation page, set the onload event to redirect to actually do the download.
<body onload=window.location='/file/download/{{ file.name }}/'>
You can do it using ajax request waiting until the download fully successful.
in your view :
$.fileDownload('some/file.pdf')
.done(function () { //redirect
window.location = '/link';
})
.fail(function () { alert('File download failed!'); });
How to use the previous code:
first add a name or id or class to your link
download link
next: here i use id to identify the link #a_d*
<script type="text/javascript">
$(document).on("click", "#a_d", function () {
$.fileDownload(.done(function () { //redirect
window.location = '/link';})
});
});
</script>
done !!