views.py 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177
  1. from django.shortcuts import render
  2. from django.views import generic
  3. from django.views.generic import TemplateView
  4. from .models import Product, Credit, Description, Vote, Contact, Interaction, Media, Video, Link, Category
  5. from django.db import models
  6. from django.contrib.auth.models import User
  7. from django.contrib.auth.mixins import LoginRequiredMixin
  8. from django.core import serializers
  9. from django.core.mail import send_mail
  10. from django.contrib.auth.decorators import login_required
  11. from django.contrib.auth.models import User, Group
  12. from django.http import HttpResponseRedirect
  13. from django.urls import reverse
  14. from django.core.files import File
  15. from django.http import HttpResponse
  16. from django.views.generic import FormView
  17. from django.contrib.auth import login, authenticate
  18. from django.shortcuts import render, redirect
  19. from django.forms import formset_factory
  20. from django.forms import BaseModelFormSet
  21. from django.forms import modelformset_factory, inlineformset_factory
  22. from .forms import LinkFormSet, LinkForm, FormsetHelper, MediaFormsetHelper, MediaFormSet
  23. from django.contrib import messages
  24. from django_file_form.uploader import FileFormUploader
  25. from django_countries import countries
  26. from django.template import Context, Template
  27. from django.conf import settings
  28. from constance import config
  29. from django.http import Http404
  30. from django.db.models import Count
  31. from PIL import Image
  32. from PIL import ImageFont
  33. from PIL import ImageDraw
  34. from django.db.models import Q
  35. from django.shortcuts import get_list_or_404, get_object_or_404
  36. from .forms import RegisterForm, SignUpForm, DescriptionForm,SubmissionForm,CreditForm,DescriptionForm,InteractionForm,LinkForm,MediaForm,VideoForm, MediaForm_test, MediaForm1, MediaForm2
  37. import os
  38. import itertools
  39. from PIL import Image
  40. import json
  41. import copy
  42. import csv
  43. # Create your views here.
  44. def index(request):
  45. context = {}
  46. return render(request, 'index.html', context = context)
  47. def about(request):
  48. context = {}
  49. context = {'about_text': Template(config.ABOUT_CONTENT).render(Context(context))}
  50. return render(request, 'marktplatz/about.html', context)
  51. #template = Template( config.ABOUT_CONTENT )
  52. #return HttpResponse( template.render( Context(context) ) )
  53. #return render(request, rendered , context = context)
  54. def submit(request):
  55. context = {}
  56. context = {'submit_text': Template(config.SUBMIT_TEXT).render(Context(context))}
  57. return render(request,'marktplatz/submit.html', context)
  58. def error_404_view(request, exception):
  59. data = {"name": "ThePythonDjango.com"}
  60. return render(request,'marktplatz/error_404.html', data)
  61. @login_required
  62. def home(request):
  63. user = request.user
  64. if user.groups.filter(name='submission').exists():
  65. return HttpResponseRedirect(reverse('MyProducts'))
  66. else:
  67. return HttpResponseRedirect(reverse('Products'))
  68. class ProductsView(generic.ListView):
  69. model = Product
  70. #context_object_name = 'Products'
  71. # show the best 4 website finish
  72. def get_queryset(self):
  73. # original qs
  74. qs = super().get_queryset()
  75. self.user = self.request.user
  76. user = self.user
  77. if user.groups.filter(name='jury').exists():
  78. return qs.filter(sumbitted = config.CURRENT_EVENT)
  79. if user.groups.filter(name='submission').exists():
  80. contact = Contact.objects.get(user=user)
  81. return qs.filter(contact = contact)
  82. if user.is_superuser:
  83. return qs
  84. return qs.filter(public = True)
  85. def get_context_data(self, **kwargs):
  86. context = super().get_context_data(**kwargs)
  87. user =self.request.user
  88. context['user'] = user
  89. used_countries = []
  90. years = {''}
  91. for Product in context['product_list']:
  92. if not years.__contains__(Product.year):
  93. years.add(Product.year)
  94. for country in Product.country:
  95. if not used_countries.__contains__(country):
  96. used_countries.append(country)
  97. years.remove('')
  98. context['year_list'] = years
  99. context['count_list'] = used_countries
  100. context['cat_list'] = Category.objects.all
  101. context['sponsor_cards'] = Template( config.SPONSOR_CARDS ).render( Context(context) )
  102. context['main_card'] = Template( config.MAIN_CARD ).render( Context(context) )
  103. return context
  104. template_name = 'marktplatz/product_overview.html'
  105. class DetailView(generic.DetailView):
  106. model = Product
  107. template_name = 'marktplatz/Product_detail.html'
  108. def get_context_data(self, **kwargs):
  109. context = super().get_context_data(**kwargs)
  110. context['credits'] = Credit.objects.select_related().get(Product = self.kwargs['pk'])
  111. context['descriptions'] = Description.objects.select_related().get(Product = self.kwargs['pk'])
  112. context['interactions'] = Interaction.objects.select_related().get(Product=self.kwargs['pk'])
  113. context['PAUI'] = Category.objects.get(short_name='PAUI')
  114. return context
  115. def post(self, request, *args, **kwargs):
  116. vote = int(request.POST['vote'])
  117. comment = str(request.POST['comment'])
  118. if vote <= 10:
  119. try:
  120. get_vote = Vote.objects.get(juryMember=self.request.user, Product=self.kwargs['pk'])
  121. get_vote.vote = vote
  122. get_vote.comment = comment
  123. get_vote.save()
  124. except Vote.DoesNotExist:
  125. get_vote = Vote(Product = Product.objects.get(pk=self.kwargs['pk']), juryMember= self.request.user, vote = vote, comment=comment)
  126. get_vote.save()
  127. else:
  128. return HttpResponseRedirect(request.path)
  129. return HttpResponseRedirect(reverse('Products'))
  130. class VoteView(LoginRequiredMixin, generic.ListView):
  131. model = Product
  132. template_name='marktplatz/voteDetail.html'
  133. def get_context_data(self, **kwargs):
  134. context = super().get_context_data(**kwargs)
  135. context['user'] = User.objects.filter(groups__name='JuryMembers')
  136. return context
  137. class CidView(LoginRequiredMixin, generic.ListView):
  138. model = Product
  139. template_name='marktplatz/votes_cid.html'
  140. def get_context_data(self, **kwargs):
  141. context = super().get_context_data(**kwargs)
  142. return context
  143. def post(self, request, *args, **kwargs):
  144. for pk in request.POST.dict():
  145. if not 'csrfmiddlewaretoken' in pk:
  146. if request.POST[pk] != '' and ('cid' in pk):
  147. now_Product = Product.objects.get(pk=pk.split('.')[0])
  148. now_Product.class_cid = request.POST[pk]
  149. now_Product.save()
  150. if request.POST[pk] != '' and ('sub' in pk):
  151. now_Product = Product.objects.get(pk=pk.split('.')[0])
  152. now_Product.sumbitted = request.POST[pk]
  153. now_Product.save()
  154. return HttpResponseRedirect('')
  155. class AdminView(LoginRequiredMixin, generic.ListView):
  156. model = Product
  157. template_name='marktplatz/admin_panel.html'
  158. def get_context_data(self, **kwargs):
  159. context = super().get_context_data(**kwargs)
  160. return context
  161. def post(self, request, *args, **kwargs):
  162. for pk in request.POST.dict():
  163. print(pk)
  164. print("test")
  165. if not 'csrfmiddlewaretoken' in pk:
  166. if request.POST[pk] != '' and ('public' in pk):
  167. pass
  168. #now_Product = Product.objects.get(pk=pk.split('.')[0])
  169. #now_Product.public = request.POST[pk].checktest
  170. #now_Product.save()
  171. if request.POST[pk] != '' and ('edit' in pk):
  172. pass
  173. #now_Product = Product.objects.get(pk=pk.split('.')[0])
  174. #now_Product.edit = request.POST[pk].checktest
  175. #now_Product.save()
  176. return HttpResponseRedirect('')
  177. class importOldProducts(LoginRequiredMixin, TemplateView):
  178. template_name = "marktplatz/importold.html"
  179. def post(self, request):
  180. importPath = settings.IMPORT_PATH
  181. filepath = importPath+'results-survey961137.csv'
  182. context= {'faild':''}
  183. faild='Log: \n'
  184. from1 =int(request.POST['from'])
  185. to =int(request.POST['to'])
  186. with open(filepath, newline='', encoding='utf8') as csvfile:
  187. fieldnames=['Response ID','Date submitted','Last page','Start language','Seed','Date started','Date last action','IP address','Referrer URL','Name [First name]','Name [Last name]','Address [Street number & name]','Address [Postcode]','Address [City]','Address [Country]','Contact Details','Email address','Phone Number','Alternate phone number','Skype name','Website','News','I submit the following Product to take part in the: [Exhibition]','I submit the following Product to take part in the: [Awards]','In the following categories [Animated architecture]','In the following categories [Spatial media art]','In the following categories [Participatory architecture & urban interaction]','In the following categories [Money architecture]','In the following categories [Future trends & prototypes]','Product title','Country','City','Year of completion','Teaser text','Description (header)','Description (long text)','Credits [Building or Product owner]','Credits [Architecture]','Credits [Product artist/concept/design/planning]','Credits [Structural engineering]','Credits [Facade design]','Credits [Facade construction]','Credits [Kinetic engineering]','Credits [Light design]','Credits [Technical layout light (LED technical layout)]','Credits [Display content/ visuals/ showreel]','Credits [Light hardware (LED hardware)]','Credits [Lighting control software]','Credits [Product co-ordination]','Credits [Membrane skin]','Credits [Interaction design/ programming]','Credits [Product sponsor/ support]','Credits [Pixel or other basic module/ elements]','Facade type and geometry (structure)','Kind of light creation','Resolution and transmitting behaviour','Pixel distance','Urban situation','Description of showreel','Community or communities involved','Host organization','Legal form','Issues addressed','Impact','Tools developed','Tools used','Next steps','Link','Other links [Link 1]','Other links [Link 2]','Other links [Link 3]','Will you bring objects to the exhibition?','If yes - what would you bring? (select all that apply) [Prototype]','If yes - what would you bring? (select all that apply) [Comment]','If yes - what would you bring? (select all that apply) [Product sample]','If yes - what would you bring? (select all that apply) [Comment]','If yes - what would you bring? (select all that apply) [Model]','If yes - what would you bring? (select all that apply) [Comment]','If yes - what would you bring? (select all that apply) [Something else (please specify)]','If yes - what would you bring? (select all that apply) [Comment]','Other information [Field title]','Other information [Content]','Other information [Field title]','Other information [Content]','Other information [Field title]','Other information [Content]','Comments','Picture of the Product0','filecount0','Credit0','Picture of the Product1','filecount1','Credit1','Picture of the Product2','filecount2','Credit2','Picture of the Product3','filecount3','Credit3','Picture of the Product4','filecount4','Credit4','Picture of the Product5','filecount5','Credit5','Do you authorize the use of the submited files?','Terms of participation. Please download the terms of participation, sign them and submit a scanned copy of the signed document here. ','filecount - Terms of participation. Please download the terms of participation, sign them and submit a scanned copy of the signed document here. ','Whom else should we ask in order to get information about the Product? Please indicate contact information.','Which companies were involved in the Product and could be willing to support the Biennale, and might be interested in presenting the Product and the technology / products used in the Product?','You are also welcome to make other suggestions for the Media Architecture Biennale in general:']
  188. reader = csv.DictReader(csvfile, delimiter=';',fieldnames=fieldnames)
  189. reader.__next__()
  190. counter = 0;
  191. while(counter< from1):
  192. reader.__next__()
  193. counter += 1
  194. for row in reader:
  195. if(counter > to):
  196. break
  197. counter+=1
  198. Product = Product()
  199. #4 the contact
  200. contact = Contact()
  201. contact.first_name =row['Name [First name]']
  202. contact.last_name =row['Name [Last name]']
  203. contact.adress =row['Address [Street number & name]']
  204. contact.postcode =row['Address [Postcode]']
  205. contact.city =row['Address [City]']
  206. contact.country =row['Address [Country]']
  207. contact.email =row['Email address']
  208. contact.phonenumber =row['Phone Number']
  209. contact.skype_name =row['Skype name']
  210. contact.website =row['Website']
  211. contact.alternate_phonenumber =row['Alternate phone number']
  212. contact.save()
  213. credit = Credit()
  214. credit.owner =row['Credits [Building or Product owner]']
  215. credit.architecture =row['Credits [Architecture]']
  216. credit.concept =row['Credits [Product artist/concept/design/planning]']
  217. credit.structural_engeneering =row['Credits [Structural engineering]']
  218. credit.facade_design =row['Credits [Facade design]']
  219. credit.face_construction =row['Credits [Facade construction]']
  220. credit.kinetic_design =row['Credits [Kinetic engineering]']
  221. credit.light_design =row['Credits [Light design]']
  222. credit.tecnical_layout =row['Credits [Technical layout light (LED technical layout)]']
  223. credit.display_content =row['Credits [Display content/ visuals/ showreel]']
  224. credit.light_hardware =row['Credits [Light hardware (LED hardware)]']
  225. credit.lightning_software =row['Credits [Lighting control software]']
  226. credit.Product_coordination =row['Credits [Product co-ordination]']
  227. credit.membrane_skin =row['Credits [Membrane skin]']
  228. credit.interaction_design =row['Credits [Interaction design/ programming]']
  229. credit.sponsor =row['Credits [Product sponsor/ support]']
  230. #Credits [Pixel or other basic module/ elements]
  231. credit.save()
  232. interaction = Interaction()
  233. interaction.communtity =row['Community or communities involved']
  234. interaction.host =row['Host organization']
  235. interaction.legal_form =row['Legal form']
  236. interaction.issues =row['Issues addressed']
  237. interaction.impact =row['Impact']
  238. interaction.tools =row['Tools developed']
  239. interaction.tools_used =row['Tools used']
  240. interaction.next_steps =row['Next steps']
  241. interaction.save()
  242. description = Description()
  243. description.facade =row['Facade type and geometry (structure)']
  244. description.light_creation =row['Kind of light creation']
  245. description.resolution =row['Resolution and transmitting behaviour']
  246. description.pixel_distance =row['Pixel distance']
  247. #description.luminance =''
  248. description.urban_situation =row['Urban situation']
  249. description.description_showreel =row['Description of showreel']
  250. description.save()
  251. Product.title=row['Product title']
  252. Product.country = row['Country']
  253. Product.city = row['City']
  254. Product.year = row['Year of completion']
  255. Product.owner= row['Credits [Building or Product owner]']
  256. Product.teaser_txt = row['Teaser text']
  257. Product.header = row['Description (header)']
  258. Product.description_txt = row['Description (long text)']
  259. Product.interaction = interaction
  260. Product.credits = credit
  261. Product.description=description
  262. Product.contact = contact
  263. Product.cid=1
  264. Product.class_cid='1'
  265. Product.save()
  266. AA = Category.objects.get(short_name = 'AA')
  267. FP = Category.objects.get(short_name='FP')
  268. MA = Category.objects.get(short_name='MA')
  269. SMA = Category.objects.get(short_name='SMA')
  270. PAUI = Category.objects.get(short_name='PAUI')
  271. if 'Yes' in row['In the following categories [Animated architecture]']:
  272. Product.category.add(AA)
  273. if 'Yes' in row['In the following categories [Future trends & prototypes]']:
  274. Product.category.add(FP)
  275. if 'Yes' in row['In the following categories [Money architecture]']:
  276. Product.category.add(MA)
  277. if 'Yes' in row['In the following categories [Spatial media art]']:
  278. Product.category.add(SMA)
  279. if 'Yes' in row['In the following categories [Participatory architecture & urban interaction]']:
  280. Product.category.add(PAUI)
  281. Product.save()
  282. def readMedia(number):
  283. mediadetail = json.loads(row['Picture of the Product' + str(number)])[0]
  284. if 'mp4' in mediadetail['ext']:
  285. media = Video()
  286. elif 'png' in mediadetail['ext'] or 'jpg' in mediadetail['ext'] or 'png' in mediadetail['ext']:
  287. media = Media()
  288. else:
  289. return row['Product title']+' : '+ str(mediadetail) +' FILEERROR'+ '\n'
  290. media.Product = Product
  291. media.name_for = mediadetail['title']
  292. media.filename = row['Product title'] + str(number)
  293. media.copyright = row['Credit' + str(number)]
  294. file = open(importPath+mediadetail['filename'], 'rb')
  295. image = File(file)
  296. media.image.save(str(number) + '.' + mediadetail['ext'], image)
  297. if 'png' in mediadetail['ext'] or 'jpg' in mediadetail['ext'] or 'png' in mediadetail['ext']:
  298. media.image_small.save(str(number) + '_small' + '.' + mediadetail['ext'], image)
  299. media.image_medium.save(str(number) + '_medium' + '.' + mediadetail['ext'], image)
  300. media.image_big.save(str(number) + '_big' + '.' + mediadetail['ext'], image)
  301. media.image_norm.save(str(number) + '_norm' + '.' + mediadetail['ext'], image)
  302. media.save
  303. return row['Product title'] + str(mediadetail) + ' mediasucsess' + '\n'
  304. if row['filecount0'] == '1' :
  305. faild +=readMedia(0)
  306. if row['filecount1'] == '1':
  307. faild +=readMedia(1)
  308. if row['filecount2'] == '1':
  309. faild +=readMedia(2)
  310. if row['filecount3'] == '1':
  311. faild +=readMedia(3)
  312. if row['filecount4'] == '1':
  313. faild +=readMedia(4)
  314. if row['filecount5'] == '1':
  315. faild +=readMedia(5)
  316. if row['Link'] != '':
  317. Link.objects.create(Product=Product, link= row['Link'])
  318. if row['Other links [Link 1]'] != '':
  319. Link.objects.create(Product=Product, link=row['Other links [Link 1]'])
  320. if row['Other links [Link 2]'] != '':
  321. Link.objects.create(Product=Product, link=row['Other links [Link 2]'])
  322. if row['Other links [Link 3]'] != '':
  323. Link.objects.create(Product=Product, link=row['Other links [Link 3]'])
  324. faild += row['Product title'] + ' Productsuccsess' + '\n'
  325. context['faild'] = faild
  326. print(faild)
  327. return render(request, self.template_name, context)
  328. def get(self, request):
  329. context = {'faild': ''}
  330. faild=''
  331. context['faild'] = faild
  332. return render(request, self.template_name, context )
  333. class importOldJson(LoginRequiredMixin, TemplateView):
  334. template_name = "marktplatz/importold.html"
  335. def post(self, request):
  336. context = {'faild': ''}
  337. faild= ''
  338. from1 = int(request.POST['from'])
  339. to = int(request.POST['to'])
  340. def parseData(key, value,faild, ProductInst, creditInst, descriptionInst,interactionInst, cid):
  341. print('{!r} : {!r}'.format(key, value))
  342. if "Country" == key:
  343. ProductInst.country = value
  344. elif "City" == key:
  345. ProductInst.city = value
  346. elif "Year" == key:
  347. if isinstance(value,int):
  348. ProductInst.year = value
  349. elif "Owner" in key:
  350. ProductInst.owner = value
  351. creditInst.owner = value
  352. elif "Architect" in key:
  353. creditInst.architecture = value
  354. elif "Light Design" in key:
  355. creditInst.light_design = value
  356. elif "Lighting Control Software" in key:
  357. creditInst.lightning_software = value
  358. elif "Lighting Control Hardware" in key:
  359. creditInst.light_hardware = value
  360. elif "Technical Layout" in key:
  361. creditInst.technical_layout = value
  362. elif "Programming, Interaction Design" == key:
  363. creditInst.interaction_design = value
  364. elif "Product Coordination" == key:
  365. creditInst.Product_coordination = value
  366. elif "Façade Design" == key:
  367. creditInst.facade_design = value
  368. elif "Kind of Light Creation" == key:
  369. descriptionInst.light_creation = value
  370. elif "Resolution and Transmitting" in key:
  371. descriptionInst.resolution = value
  372. elif "Luminance" in key:
  373. descriptionInst.luminance = value
  374. elif "Urban Situation" == key:
  375. descriptionInst.urban_situation = value
  376. elif "cid" == key:
  377. ProductInst.class_cid = value
  378. cid = value
  379. elif "heading" == key:
  380. ProductInst.title = value
  381. elif "teaser" == key:
  382. ProductInst.teaser_txt= value
  383. elif "title" == key:
  384. ProductInst.header = value
  385. elif "description" == key:
  386. ProductInst.description_txt = value
  387. elif "Pixel Distance" in key:
  388. descriptionInst.pixel_distance = value
  389. elif "category" == key:
  390. ProductInst.save()
  391. if "Animated Architecture" in value:
  392. ProductInst.category.add(Category.objects.get(short_name='AA'))
  393. if "Spatial Media Art" in value:
  394. ProductInst.category.add(Category.objects.get(short_name='SMA'))
  395. if "Money Architecture" in value:
  396. ProductInst.category.add(Category.objects.get(short_name='MA'))
  397. if "Participatory Architecture" in value:
  398. ProductInst.category.add(Category.objects.get(short_name='PAUI'))
  399. if "Future Trends" in value:
  400. ProductInst.category.add(Category.objects.get(short_name='FP'))
  401. elif 'Façade Type and Geometry' in key:
  402. descriptionInst.facade = value
  403. elif "Product Artist/Concept/Planning" in key:
  404. creditInst.concept = value
  405. elif "Artist" in key:
  406. creditInst.concept = value
  407. elif "support" in key:
  408. creditInst.sponsor = value
  409. elif "Structural Engineering" in key:
  410. creditInst.structural_engeneering = value
  411. elif "LED" in key:
  412. creditInst.light_hardware = value
  413. elif "Showreel" in key:
  414. descriptionInst.description_showreel = value
  415. elif "Photo Credits" in key:
  416. ProductInst.photo = value
  417. elif "Video Credits" in key:
  418. ProductInst.videocts = value
  419. elif "Link 1" in key:
  420. ProductInst.save()
  421. Link.objects.create(Product=ProductInst, link=value)
  422. elif "Link 2" in key:
  423. ProductInst.save()
  424. Link.objects.create(Product=ProductInst, link=value)
  425. elif "Link 3" in key:
  426. ProductInst.save()
  427. Link.objects.create(Product=ProductInst, link=value)
  428. elif "Link 4" in key:
  429. ProductInst.save()
  430. Link.objects.create(Product=ProductInst, link=value)
  431. elif "Programming, Interaction Design" in key:
  432. creditInst.interaction_design = value
  433. elif "tables" == key:
  434. iterate_list(value, faild, ProductInst, creditInst, descriptionInst, interactionInst, cid)
  435. elif "files" == key:
  436. ProductInst.save()
  437. for file in value:
  438. print('!!!!!!!!!!!!!!!!!!!'+file)
  439. fileimg=''
  440. if 'mp4' in file or 'm3u8' in file or 'm4v' in file:
  441. media = Video()
  442. try:
  443. fileimg = open(settings.OLD_IMPORT_PATH + cid + '/' + file.split('.')[0]+'.mp4', 'rb')
  444. except:
  445. try:
  446. fileimg = open(settings.OLD_IMPORT_PATH + cid + '/' + file.split('.')[0]+'.m4v', 'rb')
  447. except:
  448. fileimg = open(settings.OLD_IMPORT_PATH + cid + '/' + file.split('.')[0]+'.m3u8', 'rb')
  449. elif 'png' in file or 'jpg' in file or 'png' in file:
  450. media = Media()
  451. fileimg = open(settings.OLD_IMPORT_PATH + cid + '/' + file, 'rb')
  452. media.Product = ProductInst
  453. media.filename = file
  454. image = File(fileimg)
  455. media.image.save(file, image)
  456. if 'png' in file or 'jpg' in file or 'png' in file:
  457. media.image_small.save(file.split('.')[0]+'_small', image)
  458. media.image_medium.save(file.split('.')[0]+'_medium', image)
  459. media.image_big.save(file.split('.')[0] +'_big', image)
  460. media.image_norm.save(file.split('.')[0] + '_norm', image)
  461. media.save
  462. return cid
  463. def iterate_rec(dictionary, faild, ProductInst, creditInst, descriptionInst, interactionInst, cid):
  464. for key, value in dictionary.items():
  465. if isinstance(value, dict):
  466. cid =iterate_rec(value, faild, ProductInst, creditInst, descriptionInst, interactionInst, cid)
  467. else:
  468. cid = parseData(key, value,faild, ProductInst, creditInst, descriptionInst,interactionInst, cid)
  469. ProductInst.save
  470. return cid
  471. def iterate_list(dictionary, faild, ProductInst, creditInst, descriptionInst, interactionInst, cid):
  472. for item in dictionary:
  473. if item == None:
  474. return
  475. cid = iterate_rec(item,faild, ProductInst, creditInst, descriptionInst,interactionInst, cid)
  476. ProductInst.save
  477. return cid
  478. def all_files(directory):
  479. for path, files, dirs in os.walk(directory):
  480. for f in dirs: yield os.path.join(path, f)
  481. olfolder = settings.OLD_IMPORT_PATH
  482. iter1= all_files(olfolder)
  483. alljason = [f for f in iter1 if f.endswith('.json')]
  484. i=0
  485. for filepath in alljason:
  486. i+=1
  487. print(filepath, i)
  488. if(i<from1):
  489. continue
  490. if(i>to):
  491. break
  492. print(filepath)
  493. faild += filepath +'\n'
  494. ProductInst = Product()
  495. creditInst = Credit()
  496. descriptionInst = Description()
  497. interactionInst = Interaction()
  498. with open(filepath, encoding='utf8') as data_file:
  499. data_file_str = data_file.read()
  500. data_file_json = json.loads(data_file_str)
  501. print ( filepath.split('/') )
  502. cid = filepath.split('/')[5]
  503. iterate_rec(data_file_json, faild, ProductInst, creditInst, descriptionInst,interactionInst, cid)
  504. ProductInst.submitted = 'old'
  505. creditInst.save()
  506. descriptionInst.save()
  507. interactionInst.save()
  508. ProductInst.credits =creditInst
  509. ProductInst.description=descriptionInst
  510. ProductInst.interaction = interactionInst
  511. ProductInst.save()
  512. context['faild'] = faild
  513. return render(request, self.template_name, context)
  514. def get(self, request):
  515. template_name = "marktplatz/importold.html"
  516. context = {'faild': ''}
  517. faild = ''
  518. context['faild'] = faild
  519. return render(request, self.template_name, context)
  520. class lightboximg(LoginRequiredMixin, TemplateView):
  521. template_name = "marktplatz/importold.html"
  522. def post(self, request):
  523. context = {'faild': ''}
  524. faild = ''
  525. from1 = int(request.POST['from'])
  526. to = int(request.POST['to'])
  527. Products = Product.objects.all()
  528. i = 0
  529. for Product in Products:
  530. i+=1
  531. if (i < from1):
  532. continue
  533. if (i > to):
  534. break
  535. medias = Product.media_set.all()
  536. for oldmedia in medias:
  537. if not oldmedia.image_norm:
  538. oldpic = oldmedia.image
  539. oldmedia.image_norm.save(oldmedia.filename() + '_norm', oldpic)
  540. oldmedia.save
  541. return render(request, self.template_name, context)
  542. def get(self, request):
  543. context = {'faild': ''}
  544. faild = ''
  545. context['faild'] = faild
  546. return render(request, self.template_name, context)
  547. class registerView(FormView):
  548. template_name = 'marktplatz/form.html'
  549. #form_class = RegisterForm
  550. def get(self, request):
  551. #form = self.form_class()
  552. context = request.GET.dict()
  553. context['form'] = RegisterForm
  554. context['signUp'] = SignUpForm
  555. return render(request, self.template_name, context)
  556. def post(self, request):
  557. print ( request.POST.dict() )
  558. form = SignUpForm(request.POST)
  559. form_contact = RegisterForm(request.POST)
  560. #
  561. # Filter existing emails
  562. #
  563. qs = Contact.objects.filter( email=form_contact.data['email'] )
  564. if ( qs.count() ):
  565. form_contact.add_error('email', "Email already in use, please reset your password.")
  566. if form.is_valid() and form_contact.is_valid():
  567. print (form.cleaned_data)
  568. print (form_contact.cleaned_data)
  569. contact = form_contact.save(commit=False)
  570. user = form.save()
  571. user.email = contact.email
  572. user.first_name = contact.first_name
  573. user.last_name = contact.last_name
  574. user.set_password(form.cleaned_data.get('password1'))
  575. user.save()
  576. contact.user = user
  577. contact.save()
  578. username = form.cleaned_data.get('username')
  579. raw_password = form.cleaned_data.get('password1')
  580. group = Group.objects.get(name='submission')
  581. group.user_set.add(user)
  582. user = authenticate(username=username, password=raw_password)
  583. if user is not None:
  584. # A backend authenticated the credentials
  585. login(request, user)
  586. return redirect('Products')
  587. else:
  588. # No backend authenticated the credentials
  589. send_mail(
  590. 'error with auth',
  591. 'Error in authorization.' + json.dumps( request.POST.dict() ),
  592. 'awards@berta.mediaarchitecture.org',
  593. ['juan@mediaarchitecture.org'],
  594. fail_silently=False,
  595. )
  596. return redirect('Products')
  597. login(request, user)
  598. else:
  599. print (form.errors)
  600. print (form_contact.errors)
  601. send_mail(
  602. 'error with auth',
  603. 'Error in forms. \n\n form.errors: \n\n' + json.dumps(form.errors) + '\n\n form_contact.errors: \n\n' + json.dumps(form_contact.errors),
  604. 'awards@berta.mediaarchitecture.org',
  605. ['juan@mediaarchitecture.org'],
  606. fail_silently=False,
  607. )
  608. context = request.POST.dict()
  609. context['signUp'] = form
  610. context['form'] = form_contact
  611. context['signup_errors'] = form.errors
  612. context['contact_errors'] = form_contact.errors
  613. return render(request, self.template_name, context)
  614. # if form_contact.is_valid():
  615. # contact = form_contact.save(commit=False)
  616. # contact.user = user
  617. # contact.save()
  618. #
  619. # return redirect('Products')
  620. context = request.GET.dict()
  621. context['form'] = RegisterForm
  622. context['signUp'] = SignUpForm
  623. return render(request, self.template_name, context)
  624. class NewSubmitView(LoginRequiredMixin, FormView):
  625. use_ajax = True
  626. template_name = 'marktplatz/add.html'
  627. #model = Product
  628. def get(self, request,*args, **kwargs):
  629. # form = self.form_class()
  630. context = request.GET.dict()
  631. context['Product'] = SubmissionForm
  632. context['credits'] = CreditForm
  633. context['description'] = DescriptionForm
  634. context['interaction'] = InteractionForm
  635. context['lnks'] = LinkFormSet
  636. context['lnks_helper'] = FormsetHelper()
  637. context['use_ajax'] = True
  638. context['info_txt'] = Template(config.INFO_TXT).render(Context(context))
  639. return render(request, self.template_name, context)
  640. def post(self, request):
  641. Product_f = SubmissionForm(request.POST, request.FILES)
  642. credits_f = CreditForm(request.POST)
  643. description_f = DescriptionForm(request.POST)
  644. interaction_f = InteractionForm(request.POST)
  645. lnks_f = LinkFormSet(request.POST)
  646. vid1_f = VideoForm(request.POST, request.FILES)
  647. if Product_f.is_valid():
  648. Product = Product_f.save(commit=False)
  649. credits = credits_f.save(commit=False)
  650. description =description_f.save(commit=False)
  651. interaction =interaction_f.save(commit=False)
  652. credits.save()
  653. description.save()
  654. interaction.save()
  655. Product.credits = credits
  656. Product.description = description
  657. Product.interaction = interaction
  658. Product.contact = Contact.objects.get(user = self.request.user)
  659. Product.edit=True
  660. Product.public = False
  661. Product.sumbitted = config.CURRENT_EVENT
  662. Product.save()
  663. Product_f.save_m2m()
  664. for lnk in lnks_f:
  665. if lnk.is_valid():
  666. lnk_ = lnk.save(commit=False)
  667. lnk_.Product=Product
  668. lnk_.save()
  669. if 'addImage' in request.POST:
  670. return HttpResponseRedirect(reverse('add-Image', kwargs={'pk': Product.pk}))
  671. return HttpResponseRedirect(reverse('MyProducts'))
  672. else:
  673. context = request.POST.dict()
  674. context['Product'] = Product_f
  675. context['credits'] = credits_f
  676. context['description'] = description_f
  677. context['interaction'] = interaction_f
  678. context['lnks'] = lnks_f
  679. context['lnks_helper'] = FormsetHelper()
  680. context['use_ajax'] = True
  681. return render(request, self.template_name, context)
  682. class uploadView(LoginRequiredMixin, FormView):
  683. use_ajax = True
  684. template_name = 'marktplatz/file_upload.html'
  685. def get(self, request, pk):
  686. user = self.request.user
  687. contact = Contact.objects.get(user=user)
  688. if not Product.objects.filter(contact=contact).filter(pk=pk).exists():
  689. raise Http404
  690. Product = Product.objects.get(pk=pk)
  691. photo = Product.media_set.count()
  692. video = Product.video_set.count()
  693. context = request.GET.dict()
  694. contact = Contact.objects.get(user=self.request.user)
  695. Product = get_object_or_404(Product, (Q(pk=pk) & Q(contact=contact)))
  696. context['Product'] = Product
  697. context['images'] = Media.objects.filter(Product=Product)
  698. context['video'] = Video.objects.filter(Product=Product)
  699. context['media'] = MediaForm
  700. context['media_count'] = False
  701. context['video_count'] = False
  702. if photo >= 7:
  703. context['media_count'] = True
  704. if video >= 2:
  705. context['video_count'] = True
  706. context['use_ajax'] = True
  707. context['warning'] = False
  708. return render(request, self.template_name, context)
  709. def post(self, request, pk):
  710. vid1_f = MediaForm(request.POST, request.FILES)
  711. Product = Product.objects.get(pk=pk)
  712. i = Product.media_set.count()
  713. i += Product.video_set.count()
  714. video = Product.video_set.count()
  715. photo = Product.media_set.count()
  716. context = request.GET.dict()
  717. contact = Contact.objects.get(user=self.request.user)
  718. Product = get_object_or_404(Product, (Q(pk=pk) & Q(contact=contact)))
  719. context['Product'] = Product
  720. context['images'] = Media.objects.filter(Product=Product)
  721. context['video'] = Video.objects.filter(Product=Product)
  722. context['media'] = MediaForm
  723. context['media_count'] = False
  724. context['video_count'] = False
  725. context['use_ajax'] = True
  726. context['warning'] = False
  727. if vid1_f.is_valid():
  728. image = vid1_f.cleaned_data['image']
  729. name = image.name
  730. if 'png' in name or 'jpg' in name or 'jpeg' in name:
  731. if photo < 7:
  732. vid1 = Media()
  733. vid1.Product = Product
  734. vid1.filename = name
  735. vid1.copyright = vid1_f.cleaned_data['copyright']
  736. vid1.name_for = vid1_f.cleaned_data['name_for']
  737. vid1.image.save(name, image)
  738. vid1.image_small.save(str(i) + '_small', image)
  739. vid1.image_medium.save(str(i) + '_medium', image)
  740. vid1.image_big.save(str(i) + '_big', image)
  741. vid1.image_norm.save(str(i) + '_norm', image)
  742. vid1.save
  743. photo += 1
  744. else:
  745. context['warning'] = "You can not upload any more photos!"
  746. elif 'mp4' in name or 'm3u8' in name or 'm4v' in name:
  747. if video < 2:
  748. #TODO clean image here!
  749. vid1 = Video()
  750. vid1.Product = Product
  751. vid1.filename = name
  752. vid1.copyright = vid1_f.cleaned_data['copyright']
  753. vid1.name_for = vid1_f.cleaned_data['name_for']
  754. vid1.image.save(name, image)
  755. vid1.save
  756. video += 1
  757. else:
  758. context['warning'] = "You can not upload any more videos!"
  759. vid1_f.delete_temporary_files()
  760. if photo >= 7:
  761. context['media_count'] = True
  762. if video >= 2:
  763. context['video_count'] = True
  764. return render(request, self.template_name, context)
  765. handle_upload = FileFormUploader()
  766. class EditView(FormView):
  767. template_name = 'marktplatz/add.html'
  768. def get(self, request, pk):
  769. user = self.request.user
  770. contact = Contact.objects.get(user=user)
  771. if not Product.objects.filter(contact=contact).filter(pk=pk).exists():
  772. raise Http404
  773. context = request.GET.dict()
  774. context['Product'] = SubmissionForm(instance=Product.objects.get(pk=pk))
  775. context['credits'] = CreditForm(instance = Credit.objects.select_related().get(Product=pk))
  776. context['description'] = DescriptionForm(instance = Description.objects.select_related().get(Product=pk))
  777. context['interaction'] = InteractionForm(instance = Interaction.objects.select_related().get(Product=pk))
  778. linkFormSet = inlineformset_factory(Product,Link, form=LinkForm, extra=0)
  779. myLinkFormSet = linkFormSet(instance= Product.objects.get(pk=pk) )
  780. context['lnks'] = myLinkFormSet
  781. context['lnks_helper'] = FormsetHelper()
  782. context['use_ajax'] = True
  783. context['info_txt'] = Template(config.INFO_TXT).render(Context(context))
  784. return render(request, self.template_name, context)
  785. def post(self, request, pk):
  786. Product_f = SubmissionForm(request.POST, request.FILES, instance=Product.objects.get(pk=pk))
  787. credits_f = CreditForm(request.POST,instance = Credit.objects.select_related().get(Product=pk))
  788. description_f = DescriptionForm(request.POST,instance = Description.objects.select_related().get(Product=pk))
  789. lnks_f = LinkFormSet(request.POST,instance = Product.objects.get(pk=pk) )
  790. interaction_f = InteractionForm(request.POST,instance = Interaction.objects.select_related().get(Product=pk))
  791. vid1_f = VideoForm(request.POST, request.FILES)
  792. if Product_f.is_valid():
  793. if Product_f.has_changed():
  794. Product_f.save()
  795. if credits_f.has_changed() :
  796. credits_f.save()
  797. if description_f.has_changed() :
  798. description_f.save()
  799. if interaction_f.has_changed():
  800. interaction_f.save()
  801. Product = Product_f.save()
  802. for lnk in lnks_f:
  803. if lnk.is_valid():
  804. lnk_ = lnk.save(commit=False)
  805. lnk_.Product = Product
  806. lnk_.save()
  807. if 'addImage' in request.POST:
  808. return HttpResponseRedirect(reverse('add-Image', kwargs={'pk': pk}))
  809. return HttpResponseRedirect(reverse('MyProducts'))
  810. else:
  811. context = request.GET.dict()
  812. context['Product'] = Product_f
  813. context['credits'] = credits_f
  814. context['description'] = description_f
  815. context['interaction'] = interaction_f
  816. context['lnks'] = lnks_f
  817. context['lnks_helper'] = FormsetHelper()
  818. context['use_ajax'] = True
  819. return render(request, self.template_name, context)
  820. class UsersProducts(LoginRequiredMixin, generic.ListView):
  821. model = Product
  822. template_name='marktplatz/myProducts.html'
  823. def get_queryset(self):
  824. contact =Contact.objects.get(user=self.request.user)
  825. return Product.objects.filter(contact=contact)
  826. def get_context_data(self, **kwargs):
  827. context = super().get_context_data(**kwargs)
  828. contact = Contact.objects.get(user=self.request.user)
  829. context['user'] = self.request.user
  830. return context
  831. class MediaView(LoginRequiredMixin, TemplateView):
  832. template_name = 'marktplatz/media_overview.html'
  833. def get(self, request, pk):
  834. self.user = self.request.user
  835. user= self.user
  836. contact = Contact.objects.get(user=user)
  837. if not Product.objects.filter(contact=contact).filter(pk=pk).exists():
  838. raise Http404
  839. context = request.GET.dict()
  840. contact = Contact.objects.get(user=self.request.user)
  841. Product = get_object_or_404(Product, (Q(pk = pk) & Q(contact = contact)))
  842. context['Product'] = Product
  843. context['media'] = Media.objects.filter(Product=Product)
  844. context['video'] = Video.objects.filter(Product=Product)
  845. return render(request, self.template_name, context)
  846. def delete_media(request, pk):
  847. user = request.user
  848. contact = Contact.objects.get(user=user)
  849. object = Media.objects.get(id=pk)
  850. if not Product.objects.filter(contact=contact).filter(pk=object.Product.pk).exists():
  851. raise Http404
  852. object.delete()
  853. return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
  854. def delete_video(request, pk):
  855. user = request.user
  856. contact = Contact.objects.get(user=user)
  857. object = Video.objects.get(id=pk)
  858. if not Product.objects.filter(contact=contact).filter(pk=object.Product.pk).exists():
  859. raise Http404
  860. object.delete()
  861. return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
  862. #class datetimeadd(LoginRequiredMixin, TemplateView):
  863. #
  864. # template_name = "marktplatz/importold.html"
  865. #
  866. # def post(self, request):
  867. # context = {'faild': ''}
  868. # faild = ''
  869. # from1 = int(request.POST['from'])
  870. # to = int(request.POST['to'])
  871. #
  872. # Products = Product.objects.all()
  873. # i = 0
  874. #
  875. # for Product in Products:
  876. # i += 1
  877. # if (i < from1):
  878. # continue
  879. # if (i > to):
  880. # break
  881. #
  882. # if Product.date_submitted >
  883. #
  884. # return render(request, self.template_name, context)
  885. #
  886. # def get(self, request):
  887. # context = {'faild': ''}
  888. # faild = ''
  889. # context['faild'] = faild
  890. #
  891. # return render(request, self.template_name, context)