Django + Dropzone - I can't display files - ajax

I'm creating Django application with gallery. That gallery have albums and photos. Photos have foreign key to album.
In template I'm sending files and album id (only one person can add something to gallery, so I don't have to worry about that as a security hole). I'm sending these files with dropzone's javascript.
Then in view I use such code to save photos:
if 'addphotos' in request.POST:
if ('Album' in request.POST):
ualbum = Album.objects.get(id=request.POST['Album'])
print(ualbum.title)#just checking, this part works
files = [request.FILES.get('dzfile[%d]' % i) for i in range(0, len(request.FILES))]
for ufile in files:
p = Photo.objects.create(album=ualbum, file=ufile)
And something is not working there with files. Photo object is created but file is not attached to it.
In ./manage.py shell I did something like this:
>>> from main.models import Photo
>>> from main.models import Album
>>> album = Album.objects.get(id=8)
>>> print (album.title)
teraz zadziała
>>> photos = Photo.objects.filter(album=album)
>>> print(photos)
<QuerySet [<Photo: Photo object>, <Photo: Photo object>, <Photo: Photo object>]>
>>> for photo in photos:
... print(photo.album.title)
...
teraz zadziała
teraz zadziała
teraz zadziała
>>> for photo in photos:
... print(photo.file.url)
...
Traceback (most recent call last):
File "<console>", line 2, in <module>
File "/home/zeko/Pulpit/grh/stronka/s/lib64/python3.4/site-packages/django/db/models/fields/files.py", line 70, in url
self._require_file()
File "/home/zeko/Pulpit/grh/stronka/s/lib64/python3.4/site-packages/django/db/models/fields/files.py", line 47, in _require_file
raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)
ValueError: The 'file' attribute has no file associated with it.
Why does it happen?
Photo in my models.py:
class Photo(models.Model):
album = models.ForeignKey('Album')
file = models.ImageField(upload_to='img/')
Media in my settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Where had I did something wrong?

Related

Viewing/Editing YAML content in a window using PySimpleGUI

I am learning python and PySimpleGUI seems like a good start for exercises. With this self-exercise I'm working on, I would like to view and edit a YAML file. So far, I am able to create a prompt to browse and select a yaml. I am able to print the data in the console. But my next step is to view the yaml view PySimpleGUI window. I will work on how to edit the yaml content once I can figure out how to display it.
Here is my code:
import PySimpleGUI as sg
import yaml
from yaml.loader import SafeLoader
import os
working_directory = os.getcwd()
layout = [
[sg.Text("Shoose your yaml file:")],
[sg.InputText(key="-FILE_PATH-"),
sg.FileBrowse(initial_folder=working_directory, file_types=[("YAML Files","*.yaml")])],
[sg.Button("Submit"), sg.Exit()],
[sg.Multiline(size=(30,5), key= data)]
]
window = sg.Window("File Loader", layout).Finalize()
while True:
event, values = window.read()
if event in (sg.WIN_CLOSED, 'Exit'):
break
elif event == "Submit":
file_path = values["-FILE_PATH-"];
with open(file_path) as f:
data = yaml.load(f, Loader=SafeLoader)
# print(data)
print(values[data])
window.close()
Running this code i get this error:
Traceback (most recent call last):
File "yaml_gui.py", line 13, in <module>
[sg.Multiline(size=(30,5), key= data)]
NameError: name 'data' is not defined
I'm stuck because I am not sure why it is returning this error. The code works if I decide to just print the results in my terminal by using print(data). But when I use print(values[data]), it doesn't work.

ModuleNotFoundError: No module named 'pycaret.internal'

I am trying to deploy a ML model using Streamlit and Pycaret on Heroku.
When I try deploying the app, I get the following error:
ModuleNotFoundError: No module named 'pycaret.internal'
Traceback:
File "/app/.heroku/python/lib/python3.6/site-packages/streamlit/ScriptRunner.py", line 322, in _run_script
exec(code, module.__dict__)
File "/app/Final.py", line 11, in <module>
tuned_cat=joblib.load('Cat.pkl')
File "/app/.heroku/python/lib/python3.6/site-packages/joblib/numpy_pickle.py", line 585, in load
obj = _unpickle(fobj, filename, mmap_mode)
File "/app/.heroku/python/lib/python3.6/site-packages/joblib/numpy_pickle.py", line 504, in _unpickle
obj = unpickler.load()
File "/app/.heroku/python/lib/python3.6/pickle.py", line 1050, in load
dispatch[key[0]](self)
File "/app/.heroku/python/lib/python3.6/pickle.py", line 1338, in load_global
klass = self.find_class(module, name)
File "/app/.heroku/python/lib/python3.6/pickle.py", line 1388, in find_class
__import__(module, level=0)
I have the following dependencies in the requirements.txt file:
pycaret==1.0.0
streamlit==0.58.0
I had to go with the pycaret version 1.0 because when I chose the latest version the slug size on Heroku would go beyond 500M and it would not deploy. Compiled slug size: 552M is too large (max is 500M).
Link to Github
Final.py:
import streamlit as st
import joblib
from pycaret.classification import *
tuned_cat=joblib.load('Cat.pkl')
import tensorflow as tf
physical_devices = tf.config.list_physical_devices('CPU')
def run():
add_selectbox = st.sidebar.selectbox(
"What would you like to do?",
("Online Prediction","Batch Prediction"))
st.sidebar.info('This app is created to predict if the applicant should be granted a loan or not.')
st.title("Loan Prediction App")
if add_selectbox == 'Online Prediction':
gender = st.selectbox('Gender',['Female','Male'])
married = st.selectbox('Married',['No','Yes'])
depend = st.selectbox('Dependents',['0','1','2','3+'])
edu = st.selectbox('Education',['Graduate','Not Graduate'])
self = st.selectbox('Self Employed',['No','Yes'])
app_inc = st.number_input ('Applicant Income')
co_inc = st.number_input ('Coapplicant Income')
amt = st.number_input ('Loan Amount')
term = st.number_input ('Loan Amount Term')
credit = st.selectbox('Credit History',['0','1'])
prop_are = st.selectbox('Property Area',['Rural','Semiurban','Urban'])
output=""
test_df = pd.DataFrame()
test_df['Gender']= [gender]
test_df['Married']=[married]
test_df['Dependents']=[depend]
test_df['Education']=[edu]
test_df['Self_Employed']=[self]
test_df['ApplicantIncome']=[app_inc]
test_df['CoapplicantIncome']=[co_inc]
test_df['LoanAmount']=[amt]
test_df['Loan_Amount_Term']=[term]
test_df['Credit_History']=[credit]
test_df['Property_Area']=[prop_are]
if st.button("Predict"):
Cat_pred=predict_model(tuned_cat,data=test_df)['Label']
output = Cat_pred.values
if(output==0):
text="Rejected"
st.error(text)
elif(output==1):
text="Approved"
st.success(text)
if add_selectbox == 'Batch Prediction':
file_upload = st.file_uploader("Upload excel file for predictions", type=["xlsx"])
if file_upload is not None:
data = pd.read_excel(file_upload)
st.success('File uploaded successfully!')
Cat_pred=predict_model(tuned_cat,data=data)['Label']
data['Prediction']=Cat_pred
st.write(data)
st.markdown(get_table_download_link(data), unsafe_allow_html=True)
import base64
def get_table_download_link(df):
"""Generates a link allowing the data in a given panda dataframe to be downloaded
in: dataframe
out: href string
"""
csv = df.to_csv(index=False)
b64 = base64.b64encode(
csv.encode()
).decode() # some strings <-> bytes conversions necessary here
return f'Download csv file'
if __name__ == '__main__':
run()

how to display image from a column in sqlite database

i am developing a dictionary that display meaning and image of a word at the same time when the word is being searched.I want to display image from a column on a table in sqlite database but it is giving me error
def search(event=''):
conn = sqlite3.connect('G_DICTION.db')
cur = conn.cursor()
tex.delete(1.0, "end")
data = v.get()
cur.execute("SELECT Meaning, Image FROM DICTION WHERE Words= ?", (data,))
var = cur.fetchone()
if var:
tex.insert("end", var[0]) # accessing the meaning
else:
messagebox.showinfo("Dic", "Word not found")
#####################################
img_path = var[1] # accessing the path to the image
image_object = tk.PhotoImage(img_path) # here I'm not using PIL, but tkinter PhotoImage
ImageLabel.config(image=image_object)
ImageLabel.image = image_object
frame = tk.Frame(dictWin)
frame.place(x=50, y=395)
ImageLabel = tk.Label(frame, font=("calibra", 9), bg="white")
ImageLabel.pack(expand=True, fill=tk.BOTH, padx=65, pady=20)
this is the error below;
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Temmy\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705,
in __call__
return self.func(*args)
File "C:\Users\Temmy\.PyCharmEdu2019.1\config\scratches\newdatba.py", line 23, in search
ImageLabel.config(image=image_object)
NameError: name 'ImageLabel' is not defined
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Temmy\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705,
in __call__
return self.func(*args)
File "C:\Users\Temmy\.PyCharmEdu2019.1\config\scratches\newdatba.py", line 23, in search
ImageLabel.config(image=image_object)
NameError: name 'ImageLabel' is not defined

FileNotFoundError: No such file: 'someones_epi.nii.gzip'

I am trying to load an MRI, I keep getting the following error:
Traceback (most recent call last):
File "F:/Study/Projects/BTSaG/Programs/t3.py", line 2, in <module> epi_img = nib.load('someones_epi.nii.gzip')
File "C:\Users\AnkitaShinde\AppData\Local\Programs\Python\Python35-32\lib\site-packages\nibabel\loadsave.py", line 38, in load raise FileNotFoundError("No such file: '%s'" % filename)
FileNotFoundError: No such file: 'someones_epi.nii.gzip'
The code is used is as follows:
import nibabel as nib
epi_img = nib.load('someones_epi.nii.gzip')
epi_img_data = epi_img.get_data()
epi_img_data.shape(53, 61, 33)
import matplotlib.pyplot as plt
def show_slices(slices):
""" Function to display row of image slices """
fig, axes = plt.subplots(1, len(slices))
for i, slice in enumerate(slices):
axes[i].imshow(slice.T, cmap="gray", origin="lower")
slice_0 = epi_img_data[26, :, :]
slice_1 = epi_img_data[:, 30, :]
slice_2 = epi_img_data[:, :, 16]
show_slices([slice_0, slice_1, slice_2])
plt.suptitle("Center slices for EPI image")
I have also updated the loadsave.py file in nibabel but it didn't work. Please help.
Edit:
The earlier error was resolved. Now another error has been encountered.
Traceback (most recent call last):File "F:\Study\Projects\BTSaG\Programs\t3.py", line 2, in <module> epi_img = nib.load('someones_epi.nii.gzip')
File "C:\Users\AnkitaShinde\AppData\Local\Programs\Python\Python35-32\lib\site-packages\nibabel\loadsave.py", line 47, in load filename)
nibabel.filebasedimages.ImageFileError: Cannot work out file type of "someones_epi.nii.gzip"
This is an old question, however I may have the solution for it.
I just figured out that nibabel.save() does not allow me to have dot . or dash - in the folder names. These can exist in filenames however. In your case, the current path is:
C:\Users\AnkitaShinde\AppData\Local\Programs\Python\Python35-32\Lib\site-packages\nibabel\someones_epi.nii.gzip
I would change it to:
C:\Users\AnkitaShinde\AppData\Local\Programs\Python\Python35_32\Lib\site_packages\nibabel\someones_epi.nii.gzip
This is just to give an example. Of course, I don't mean that you actually change the names of these package folders as it might cause other errors.
The actual solution would be to move the file someones_epi.nii.gzip to the user structure, something like:
C:\Users\AnkitaShinde\Desktop\nibabel\someones_epi.nii.gzip

Unique Key Error when exporting Scrapy data to Elasticsearch

I'm attempting to use the scrapy elasticsearch pipeline (here: https://github.com/knockrentals/scrapy-elasticsearch) to put data into elasticsearch. however i get the following error, i'm aware that it's related to the ELASTICSEARCH_UNIQ_KEY value that is currently set at 'url' but i have no idea what it should be set to.
Similar posts on here recommend solutions that involve creating a field for the unique key but i don't understand what this means.
Here's my error message:
2015-08-05 11:34:40 [scrapy] ERROR: Error processing {'link': [u'http://www.meetup.com/Search-Meetup-Karlsruhe/events/192357732/'],
'title': [u'Suchen in der vernetzten Welt']}
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/twisted/internet/defer.py", line 588, in _runCallbacks
current.result = callback(current.result, *args, **kw)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scrapyelasticsearch/scrapyelasticsearch.py", line 70, in process_item
self.index_item(item)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scrapyelasticsearch/scrapyelasticsearch.py", line 52, in index_item
local_id = hashlib.sha1(item[uniq_key]).hexdigest()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scrapy/item.py", line 56, in __getitem__
return self._values[key]
KeyError: 'url'
Similar posts on here recommend solutions that involve creating a
field for the unique key but i don't understand what this means.
Declare a field in your Item with the name you configured in the ELASTICSEARCH_UNIQ_KEY.
import scrapy
class DemoItem(scrapy.Item):
url = scrapy.Field() # ELASTICSEARCH_UNIQ_KEY
class DemoSpider(scrapy.Spider):
name = 'demo'
start_urls = ['http://www.example.com']
def parse(self, response):
demoItem = DemoItem()
demoItem['url'] = response.url
yield demoItem

Resources