views.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  1. import csv
  2. import json
  3. import copy
  4. import itertools
  5. from PIL import Image
  6. from PIL import Image
  7. from PIL import ImageFont
  8. from PIL import ImageDraw
  9. from django.db import models
  10. from django.db.models import Count
  11. from django.core import serializers
  12. from django.core.files import File
  13. from django.core.mail import send_mail
  14. from django.urls import reverse, reverse_lazy
  15. from django.http import HttpResponseRedirect, Http404, HttpResponse
  16. from django.contrib import messages
  17. from django.contrib.auth import login, authenticate
  18. from django.contrib.auth.models import User
  19. from django.contrib.auth.mixins import LoginRequiredMixin
  20. from django.contrib.auth.decorators import login_required
  21. from django.contrib.auth.models import User, Group
  22. from django.views import generic
  23. from django.views.generic import TemplateView
  24. from django.views.generic import FormView
  25. from django.views.generic.edit import *
  26. from django.shortcuts import render, get_object_or_404, redirect, get_list_or_404, get_object_or_404
  27. from django.forms import formset_factory
  28. from django.forms import BaseModelFormSet
  29. from django.forms import modelformset_factory, inlineformset_factory
  30. from django.forms.models import model_to_dict
  31. from django_file_form.uploader import FileFormUploader
  32. from django_countries import countries
  33. from django.template import Context, Template
  34. from django.conf import settings
  35. from constance import config
  36. from django.db.models import Q
  37. from newsletter.forms import *
  38. from newsletter.views import *
  39. from marktplatz.models import *
  40. from .forms import *
  41. # Create your views here.
  42. def index(request):
  43. context = {}
  44. return render(request, 'index.html', context = context)
  45. def about(request):
  46. context = {}
  47. context = {'about_text': Template(config.ABOUT_CONTENT).render(Context(context))}
  48. return render(request, 'marktplatz/about.html', context)
  49. def submit(request):
  50. context = {}
  51. context = {'submit_text': Template(config.SUBMIT_TEXT).render(Context(context))}
  52. return render(request,'marktplatz/submit.html', context)
  53. def error_404_view(request, exception):
  54. data = {"name": "Markplatz"}
  55. return render(request,'marktplatz/error_404.html', data)
  56. @login_required
  57. def home(request):
  58. user = request.user
  59. if user.groups.filter(name='submission').exists():
  60. return HttpResponseRedirect(reverse('my-products'))
  61. else:
  62. return HttpResponseRedirect(reverse('products'))
  63. class AgentNewslwtterFormView(TemplateView):
  64. template_name = 'marktplatz/form_newsletter.html'
  65. embed = False
  66. def get_context_data(self, **kwargs):
  67. if self.embed :
  68. kwargs['embed'] = True
  69. kwargs['form_content'] = '<i class="fas fa-bell"></i> Suchagent einrichten'
  70. kwargs['content_a'] = 'Dein Suchagent wurde erstellt!'
  71. return super().get_context_data(**kwargs)
  72. def get(self, request, *args, **kwargs):
  73. context = self.get_context_data()
  74. context['form'] = AgentNewslwtterForm( )
  75. # print (context)
  76. return render(request, self.template_name, context )
  77. class AgentNewslwtterSubscribeView(SubscribeRequestView):
  78. action = 'subscribe'
  79. # form_class = AgentNewslwtterForm
  80. confirm = False
  81. embed = False
  82. def get_context_data(self, **kwargs):
  83. if self.embed :
  84. kwargs['embed'] = True
  85. kwargs['form_content'] = '<i class="fas fa-bell"></i> Suchagent einrichten'
  86. kwargs['content_a'] = 'Dein Suchagent wurde erstellt!'
  87. # kwargs['news_form'] = SubscribeRequestForm()
  88. return super().get_context_data(**kwargs)
  89. def post(self, request, *args, **kwargs):
  90. data = request.POST.copy()
  91. data["email"] = data["email_field"]
  92. agent_form = AgentNewslwtterForm ( data )
  93. if agent_form.is_valid():
  94. agent_form.save()
  95. else:
  96. context = {}
  97. context['form_errors'] = agent_form.errors
  98. context['form'] = agent_form
  99. return render(request, 'marktplatz/form_newsletter.html', context )
  100. if agent_form.cleaned_data['subscribe'] :
  101. # return super(SubscribeRequestView).get(self, request, *args, **kwargs)
  102. return super().post( request, *args, **kwargs )
  103. # return super(SubscribeRequestView, self).post( request, *args, **kwargs )
  104. context = {}
  105. context['content_a'] = '<br><i class="fas fa-bell"></i><br><h2>Dein Suchagent wurde erstellt!</h2>'
  106. return render(request, 'marktplatz/generic.html', context )
  107. def dispatch(self, request, *args, **kwargs):
  108. return super(SubscribeRequestView, self).dispatch( request, *args, **kwargs )
  109. class genericView(TemplateView):
  110. template_name = 'marktplatz/generic.html'
  111. def get(self, request, *args, **kwargs):
  112. instance = get_object_or_404(Wohnprojekt, pk=2 )
  113. context = {}
  114. context['object'] = model_to_dict ( instance )
  115. context['object']['myfield'] = '----------------------------'
  116. # print (context)
  117. return render(request, self.template_name, context )
  118. class pagesView(TemplateView):
  119. template_name = 'marktplatz/generic.html'
  120. def get(self, request, *args, **kwargs):
  121. context = {}
  122. context['content_a'] = "lalalala"
  123. context['content_b'] = config
  124. # print (config.items() )
  125. if 'page' in kwargs:
  126. context['content_a'] = kwargs['page']
  127. try:
  128. context['content_a'] = '<br><h2>' + kwargs['page'] + "</h2><br><br>"
  129. context['content_b'] = getattr(config , kwargs['page'], '')
  130. except KeyError:
  131. raise Http404
  132. # if config.get ( kwargs['page'] ) != None:
  133. # context['content_b'] = config.get ( kwargs['page'] )
  134. return render(request, self.template_name, context )
  135. class SearchAgentCreate(CreateView):
  136. model = SearchAgent
  137. template_name = 'marktplatz/form.html'
  138. fields = 'ort', 'email'
  139. success_url = reverse_lazy('generic')
  140. embed = False
  141. def get_context_data(self, **kwargs):
  142. if self.embed :
  143. kwargs['embed'] = True
  144. kwargs['form_content'] = '<i class="fas fa-bell"></i> Suchagent einrichten'
  145. kwargs['content_a'] = 'Dein Suchagent wurde erstellt!'
  146. # kwargs['news_form'] = SubscribeRequestForm()
  147. return super().get_context_data(**kwargs)
  148. def form_valid(self, form):
  149. super().form_valid(form)
  150. return render(self.request, 'marktplatz/generic.html',
  151. self.get_context_data(form=form))
  152. class SearchAgentDelete(DeleteView):
  153. model = SearchAgent
  154. template_name = 'marktplatz/form.html'
  155. success_url = reverse_lazy('products')
  156. def get(self, request, *args, **kwargs):
  157. searchagent = get_object_or_404(SearchAgent, pk= kwargs.get('pk') )
  158. context = {}
  159. context['form_content'] = 'Dein Suchagent wurde gelöscht!'
  160. if searchagent.hash == kwargs.get('hash'):
  161. if settings.DEBUG:
  162. return render(request, self.template_name, context )
  163. else:
  164. return super().get(self, request, *args, **kwargs)
  165. else:
  166. context['form_content'] = 'Oopala, das hat nicht geklappt.'
  167. return render(request, self.template_name, context )
  168. class ProductDelete(LoginRequiredMixin, DeleteView):
  169. model = Product
  170. template_name = 'marktplatz/product_delete.html'
  171. success_url = reverse_lazy('products')
  172. def get(self, request, *args, **kwargs):
  173. contact = get_object_or_404(Contact, user= self.request.user ) # Contact.objects.get(user=self.request.user)
  174. product = get_object_or_404(Product, pk= kwargs.get('pk') )
  175. if (contact.id == product.contact.id) :
  176. return super(ProductDelete, self).get(self, request, *args, **kwargs)
  177. else:
  178. raise Http404
  179. def post(self, request, *args, **kwargs):
  180. contact = get_object_or_404(Contact, user= self.request.user ) # Contact.objects.get(user=self.request.user)
  181. product = get_object_or_404(Product, pk= kwargs.get('pk') )
  182. if (contact.id == product.contact.id) :
  183. context = {}
  184. context['form_content'] = 'Dein Projekt wird gelöscht, wenn die Seite live ist!'
  185. if settings.DEBUG:
  186. return render(request, self.template_name, context )
  187. else:
  188. return super().post(self, request, *args, **kwargs)
  189. else:
  190. raise Http404
  191. context = {}
  192. context['form_content'] = 'Oopala, das hat nicht geklappt.'
  193. return render(request, self.template_name, context )
  194. class ProductsView(generic.ListView):
  195. model = Wohnprojekt
  196. #context_object_name = 'Products'
  197. # show the best 4 website finish
  198. def get_queryset(self):
  199. # original qs
  200. qs = super().get_queryset()
  201. self.user = self.request.user
  202. user = self.user
  203. qs = qs.order_by('frei')
  204. if user.groups.filter(name='submission').exists():
  205. contact = Contact.objects.get(user=user)
  206. return qs.filter(contact = contact)
  207. if user.is_superuser:
  208. return qs
  209. qs = qs.filter(public = True)
  210. return qs
  211. def get_context_data(self, **kwargs):
  212. context = super().get_context_data(**kwargs)
  213. user =self.request.user
  214. context['user'] = user
  215. used_countries = []
  216. orts = {}
  217. raum_agebote = {}
  218. years = {''}
  219. for product in context['wohnprojekt_list']:
  220. print ( type (product.raumangebot) )
  221. print ( repr(product.raumangebot) )
  222. # print ( dir(product.raumangebot) )
  223. print ( "----" )
  224. print ( product.raumangebot.__dict__ )
  225. print ( "xxxx" )
  226. dir(MultiSelectField)
  227. print ( dir(product.raumangebot.choices ) )
  228. # print ( product.get_raumangebot_display )
  229. # print ( product.raumangebot.max_length )
  230. #
  231. # print ( product.raumangebot.to_python() )
  232. if not years.__contains__(product.year):
  233. years.add(product.year)
  234. for country in product.country:
  235. if not used_countries.__contains__(country):
  236. used_countries.append(country)
  237. # if not used_orts.__contains__( product.get_ort_display() ):
  238. if not product.ort in orts:
  239. orts[product.ort] = product.get_ort_display()
  240. # print (product.raumangebot.get_list() )
  241. for raum in product.raumangebot:
  242. print(raum)
  243. # print(raum.get_display() )
  244. if not (raum in raum_agebote):
  245. raum_agebote[raum] = product.raumangebot.choices[raum]
  246. years.remove('')
  247. context['year_list'] = years
  248. context['count_list'] = used_countries
  249. context['frei_list'] = Product.FREI
  250. context['status_list'] = Product.STATUS
  251. context['ort_dict'] = orts
  252. context['raum_agebote_dict'] = raum_agebote
  253. context['altneu_list'] = Wohnprojekt.ALTNEU
  254. context['sponsor_cards'] = Template( config.SPONSOR_CARDS ).render( Context(context) )
  255. context['main_card'] = Template( config.MAIN_CARD ).render( Context(context) )
  256. context['textSearchForm'] = textSearchForm()
  257. return context
  258. # def get(self, request, *args, **kwargs):
  259. # print ("")
  260. template_name = 'marktplatz/product_overview.html'
  261. class SearchProductsView(ProductsView):
  262. def get_queryset(self, qfilter=None, **kwargs ):
  263. # original qs
  264. qs = super().get_queryset()
  265. self.user = self.request.user
  266. user = self.user
  267. if qfilter!=None:
  268. qs = qs.filter (name__icontains= qfilter) | qs.filter (claim__icontains= qfilter) | qs.filter (beschreibung__icontains= qfilter) | qs.filter (learning__icontains= qfilter) | qs.filter (status__icontains= qfilter) | qs.filter (adresse__icontains= qfilter) | qs.filter (plz__icontains= qfilter) | qs.filter (adresse__icontains= qfilter) | qs.filter (ort__icontains= qfilter) | qs.filter (website__icontains= qfilter) | qs.filter (email__icontains= qfilter) | qs.filter (kfrei__icontains= qfilter) | qs.filter (rechtsform__icontains= qfilter) | qs.filter (orga__icontains= qfilter)
  269. qs = qs.order_by('frei')
  270. return qs.filter(public = True)
  271. def post(self, request, *args, **kwargs):
  272. qform = textSearchForm( request.POST )
  273. if qform.is_valid():
  274. self.object_list = self.get_queryset(qfilter= qform.cleaned_data["searchText"] )
  275. allow_empty = self.get_allow_empty()
  276. if not allow_empty:
  277. # When pagination is enabled and object_list is a queryset,
  278. # it's better to do a cheap query than to load the unpaginated
  279. # queryset in memory.
  280. if self.get_paginate_by(self.object_list) is not None and hasattr(self.object_list, 'exists'):
  281. is_empty = not self.object_list.exists()
  282. else:
  283. is_empty = not self.object_list
  284. if is_empty:
  285. raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.") % {
  286. 'class_name': self.__class__.__name__,
  287. })
  288. context = self.get_context_data()
  289. return self.render_to_response(context)
  290. class DetailView(generic.DetailView):
  291. model = Product
  292. template_name = 'marktplatz/product_detail.html'
  293. embed = False
  294. def get_context_data(self, **kwargs):
  295. # context = super().get_context_data(**kwargs)
  296. if self.embed :
  297. kwargs['embed'] = True
  298. # context['credits'] = Credit.objects.select_related().get(product = self.kwargs['pk'])
  299. # context['wohnprojekt'] = self.object.wohnprojekt
  300. return super().get_context_data(**kwargs)
  301. def post(self, request, *args, **kwargs):
  302. vote = int(request.POST['vote'])
  303. comment = str(request.POST['comment'])
  304. if vote <= 10:
  305. try:
  306. get_vote = Vote.objects.get(juryMember=self.request.user, product=self.kwargs['pk'])
  307. get_vote.vote = vote
  308. get_vote.comment = comment
  309. get_vote.save()
  310. except Vote.DoesNotExist:
  311. get_vote = Vote(product = Product.objects.get(pk=self.kwargs['pk']), juryMember= self.request.user, vote = vote, comment=comment)
  312. get_vote.save()
  313. else:
  314. return HttpResponseRedirect(request.path)
  315. return HttpResponseRedirect(reverse('products'))
  316. class CardDetailView(DetailView):
  317. template_name = 'marktplatz/product_detail_card.html'
  318. class AdminView(LoginRequiredMixin, generic.ListView):
  319. model = Product
  320. template_name='marktplatz/admin_panel.html'
  321. def get_context_data(self, **kwargs):
  322. context = super().get_context_data(**kwargs)
  323. return context
  324. def post(self, request, *args, **kwargs):
  325. # print (request.POST.dict())
  326. context = request.POST.dict()
  327. public = {k: v for k, v in context.items() if k.startswith('product_p')}
  328. for elemk in public:
  329. # print(elemk + " - " + public[elemk] )
  330. keys = elemk.split(".")
  331. current_product = Product.objects.get(pk=keys[1])
  332. if public[elemk] == 'true':
  333. current_product.public = True
  334. current_product.save()
  335. else:
  336. current_product.public = False
  337. current_product.save()
  338. edit = {k: v for k, v in context.items() if k.startswith('product_e')}
  339. # print (edit)
  340. for elemk in edit:
  341. # print(elemk + " - " + edit[elemk] )
  342. keys = elemk.split(".")
  343. current_product = Product.objects.get(pk=keys[1])
  344. if edit[elemk] == 'true':
  345. current_product.edit = True
  346. current_product.save()
  347. else:
  348. current_product.edit = False
  349. current_product.save()
  350. return HttpResponseRedirect('')
  351. class ProductsListView(generic.ListView):
  352. model = Product
  353. template_name='marktplatz/product_list.html'
  354. embed = False
  355. def get_context_data(self, **kwargs):
  356. if self.embed :
  357. kwargs['embed'] = True
  358. return super().get_context_data(**kwargs)
  359. def post(self, request, *args, **kwargs):
  360. # print (request.POST.dict())
  361. context = request.POST.dict()
  362. public = {k: v for k, v in context.items() if k.startswith('product_p')}
  363. for elemk in public:
  364. # print(elemk + " - " + public[elemk] )
  365. keys = elemk.split(".")
  366. current_product = Product.objects.get(pk=keys[1])
  367. if public[elemk] == 'true':
  368. current_product.public = True
  369. current_product.save()
  370. else:
  371. current_product.public = False
  372. current_product.save()
  373. edit = {k: v for k, v in context.items() if k.startswith('product_e')}
  374. # print (edit)
  375. for elemk in edit:
  376. # print(elemk + " - " + edit[elemk] )
  377. keys = elemk.split(".")
  378. current_product = Product.objects.get(pk=keys[1])
  379. if edit[elemk] == 'true':
  380. current_product.edit = True
  381. current_product.save()
  382. else:
  383. current_product.edit = False
  384. current_product.save()
  385. return HttpResponseRedirect('')
  386. class lightboximg(LoginRequiredMixin, TemplateView):
  387. template_name = "marktplatz/importold.html"
  388. def post(self, request):
  389. context = {'faild': ''}
  390. faild = ''
  391. from1 = int(request.POST['from'])
  392. to = int(request.POST['to'])
  393. products = Product.objects.all()
  394. i = 0
  395. for product in products:
  396. i+=1
  397. if (i < from1):
  398. continue
  399. if (i > to):
  400. break
  401. medias = product.media_set.all()
  402. for oldmedia in medias:
  403. if not oldmedia.image_norm:
  404. oldpic = oldmedia.image
  405. oldmedia.image_norm.save(oldmedia.filename() + '_norm', oldpic)
  406. oldmedia.save
  407. return render(request, self.template_name, context)
  408. def get(self, request):
  409. context = {'faild': ''}
  410. faild = ''
  411. context['faild'] = faild
  412. return render(request, self.template_name, context)
  413. class registerView(FormView):
  414. template_name = 'marktplatz/form.html'
  415. # form_class = RegisterForm
  416. def get(self, request):
  417. # form = self.form_class()
  418. context = request.GET.dict()
  419. context['form'] = RegisterForm
  420. context['signUp'] = SignUpForm
  421. return render(request, self.template_name, context)
  422. def post(self, request):
  423. # print ( request.POST.dict() )
  424. form = SignUpForm(request.POST)
  425. form_contact = RegisterForm(request.POST)
  426. #
  427. # Filter existing emails
  428. #
  429. qs = Contact.objects.filter( email=form_contact.data['email'] )
  430. if ( qs.count() ):
  431. form_contact.add_error('email', "Email already in use, please reset your password.")
  432. if form.is_valid() and form_contact.is_valid():
  433. # print (form.cleaned_data)
  434. # print (form_contact.cleaned_data)
  435. contact = form_contact.save(commit=False)
  436. user = form.save()
  437. user.email = contact.email
  438. user.first_name = contact.first_name
  439. user.last_name = contact.last_name
  440. user.set_password(form.cleaned_data.get('password1'))
  441. user.save()
  442. contact.user = user
  443. contact.save()
  444. username = form.cleaned_data.get('username')
  445. raw_password = form.cleaned_data.get('password1')
  446. group = Group.objects.get(name='submission')
  447. group.user_set.add(user)
  448. user = authenticate(username=username, password=raw_password)
  449. if user is not None:
  450. # A backend authenticated the credentials
  451. login(request, user)
  452. return redirect('products')
  453. else:
  454. # No backend authenticated the credentials
  455. send_mail(
  456. 'error with auth',
  457. 'Error in authorization.' + json.dumps( request.POST.dict() ),
  458. 'awards@berta.mediaarchitecture.org',
  459. ['juan@mediaarchitecture.org'],
  460. fail_silently=False,
  461. )
  462. return redirect('products')
  463. login(request, user)
  464. else:
  465. # print (form.errors)
  466. # print (form_contact.errors)
  467. send_mail(
  468. 'error with auth',
  469. '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),
  470. 'awards@berta.mediaarchitecture.org',
  471. ['juan@mediaarchitecture.org'],
  472. fail_silently=False,
  473. )
  474. context = request.POST.dict()
  475. context['signUp'] = form
  476. context['form'] = form_contact
  477. context['signup_errors'] = form.errors
  478. context['contact_errors'] = form_contact.errors
  479. return render(request, self.template_name, context)
  480. context = request.GET.dict()
  481. context['form'] = RegisterForm
  482. context['signUp'] = SignUpForm
  483. return render(request, self.template_name, context)
  484. class NewProductView(LoginRequiredMixin, FormView):
  485. use_ajax = True
  486. template_name = 'marktplatz/add.html'
  487. model = Product
  488. class NewWohnprojektView(LoginRequiredMixin, FormView):
  489. use_ajax = True
  490. template_name = 'marktplatz/add.html'
  491. model = Product
  492. def get(self, request,*args, **kwargs):
  493. # form = self.form_class()
  494. context = request.GET.dict()
  495. context['product'] = WohnprojektForm
  496. context['use_ajax'] = True
  497. context['info_txt'] = Template(config.INFO_TXT).render(Context(context))
  498. return render(request, self.template_name, context)
  499. def post(self, request):
  500. product_f = WohnprojektForm(request.POST, request.FILES)
  501. if product_f.is_valid():
  502. product = product_f.save(commit=False)
  503. product.contact = Contact.objects.get(user = self.request.user)
  504. product.edit=True
  505. product.public = False
  506. product.sumbitted = config.CURRENT_EVENT
  507. product.save()
  508. # product_f.save_m2m()
  509. if 'addImage' in request.POST:
  510. return HttpResponseRedirect(reverse('add-Image', kwargs={'pk': product.pk}))
  511. return HttpResponseRedirect(reverse('my-products'))
  512. else:
  513. context = request.POST.dict()
  514. context['product'] = product_f
  515. context['product_errors'] = product_f.errors
  516. context['use_ajax'] = True
  517. return render(request, self.template_name, context)
  518. class uploadView(LoginRequiredMixin, FormView):
  519. use_ajax = True
  520. template_name = 'marktplatz/file_upload.html'
  521. def get(self, request, pk):
  522. user = self.request.user
  523. contact = Contact.objects.get(user=user)
  524. if not Product.objects.filter(contact=contact).filter(pk=pk).exists():
  525. raise Http404
  526. product = Product.objects.get(pk=pk)
  527. photo = product.media_set.count()
  528. video = product.video_set.count()
  529. context = request.GET.dict()
  530. contact = Contact.objects.get(user=self.request.user)
  531. product = get_object_or_404(Wohnprojekt, (Q(pk=pk) & Q(contact=contact)))
  532. context['product'] = product
  533. context['images'] = Media.objects.filter(product=product)
  534. context['video'] = Video.objects.filter(product=product)
  535. context['media'] = MediaForm
  536. context['media_count'] = False
  537. context['video_count'] = False
  538. if photo >= 7:
  539. context['media_count'] = True
  540. if video >= 2:
  541. context['video_count'] = True
  542. context['use_ajax'] = True
  543. context['warning'] = False
  544. return render(request, self.template_name, context)
  545. def post(self, request, pk):
  546. vid1_f = MediaForm(request.POST, request.FILES)
  547. product = Product.objects.get(pk=pk)
  548. i = product.media_set.count()
  549. i += product.video_set.count()
  550. video = product.video_set.count()
  551. photo = product.media_set.count()
  552. context = request.GET.dict()
  553. contact = Contact.objects.get(user=self.request.user)
  554. product = get_object_or_404(Product, (Q(pk=pk) & Q(contact=contact)))
  555. context['product'] = product
  556. context['images'] = Media.objects.filter(product=product)
  557. context['video'] = Video.objects.filter(product=product)
  558. context['media'] = MediaForm
  559. context['media_count'] = False
  560. context['video_count'] = False
  561. context['use_ajax'] = True
  562. context['warning'] = False
  563. if vid1_f.is_valid():
  564. image = vid1_f.cleaned_data['image']
  565. name = image.name
  566. if 'png' in name or 'jpg' in name or 'jpeg' in name:
  567. if photo < 7:
  568. vid1 = Media()
  569. vid1.product = product
  570. vid1.filename = name
  571. vid1.copyright = vid1_f.cleaned_data['copyright']
  572. vid1.name_for = vid1_f.cleaned_data['name_for']
  573. vid1.image.save(name, image)
  574. vid1.image_small.save(str(i) + '_small', image)
  575. vid1.image_medium.save(str(i) + '_medium', image)
  576. vid1.image_big.save(str(i) + '_big', image)
  577. vid1.image_norm.save(str(i) + '_norm', image)
  578. vid1.save
  579. photo += 1
  580. else:
  581. context['warning'] = "You can not upload any more photos!"
  582. elif 'mp4' in name or 'm3u8' in name or 'm4v' in name:
  583. if video < 2:
  584. #TODO clean image here!
  585. vid1 = Video()
  586. vid1.product = product
  587. vid1.filename = name
  588. vid1.copyright = vid1_f.cleaned_data['copyright']
  589. vid1.name_for = vid1_f.cleaned_data['name_for']
  590. vid1.image.save(name, image)
  591. vid1.save
  592. video += 1
  593. else:
  594. context['warning'] = "You can not upload any more videos!"
  595. vid1_f.delete_temporary_files()
  596. if photo >= 7:
  597. context['media_count'] = True
  598. if video >= 2:
  599. context['video_count'] = True
  600. return render(request, self.template_name, context)
  601. handle_upload = FileFormUploader()
  602. class EditView(LoginRequiredMixin, FormView):
  603. template_name = 'marktplatz/add.html'
  604. def get(self, request, pk):
  605. user = self.request.user
  606. contact = Contact.objects.get(user=user)
  607. if not Product.objects.filter(contact=contact).filter(pk=pk).exists():
  608. raise Http404
  609. context = request.GET.dict()
  610. context['product'] = WohnprojektForm(instance=Wohnprojekt.objects.get(pk=pk))
  611. context['use_ajax'] = True
  612. context['info_txt'] = Template(config.INFO_TXT).render(Context(context))
  613. return render(request, self.template_name, context)
  614. def post(self, request, pk):
  615. product_f = WohnprojektForm(request.POST, request.FILES, instance=Wohnprojekt.objects.get(pk=pk))
  616. if product_f.is_valid():
  617. if product_f.has_changed():
  618. product = product_f.save( commit=False )
  619. update_fields = product_f.changed_data
  620. product.current_uri = request.build_absolute_uri( '/' ).rstrip('/')
  621. product.save( update_fields=update_fields )
  622. # product.save( )
  623. if 'addImage' in request.POST:
  624. return HttpResponseRedirect(reverse('add-Image', kwargs={'pk': pk}))
  625. return HttpResponseRedirect(reverse('my-products'))
  626. else:
  627. context = request.GET.dict()
  628. context['product'] = product_f
  629. context['product_errors'] = product_f.errors
  630. context['use_ajax'] = True
  631. return render(request, self.template_name, context)
  632. class UsersProducts(LoginRequiredMixin, generic.ListView):
  633. model = Product
  634. template_name='marktplatz/myProducts.html'
  635. def get_queryset(self):
  636. contact = Contact.objects.get(user=self.request.user)
  637. return Product.objects.filter(contact=contact)
  638. def get_context_data(self, **kwargs):
  639. context = super().get_context_data(**kwargs)
  640. contact = Contact.objects.get(user=self.request.user)
  641. context['user'] = self.request.user
  642. return context
  643. class MediaView(LoginRequiredMixin, TemplateView):
  644. template_name = 'marktplatz/media_overview.html'
  645. def get(self, request, pk):
  646. self.user = self.request.user
  647. user= self.user
  648. contact = Contact.objects.get(user=user)
  649. if not Product.objects.filter(contact=contact).filter(pk=pk).exists():
  650. raise Http404
  651. context = request.GET.dict()
  652. contact = Contact.objects.get(user=self.request.user)
  653. product = get_object_or_404(Product, (Q(pk = pk) & Q(contact = contact)))
  654. context['product'] = product
  655. context['media'] = Media.objects.filter(product=product)
  656. context['video'] = Video.objects.filter(product=product)
  657. return render(request, self.template_name, context)
  658. def delete_media(request, pk):
  659. user = request.user
  660. contact = Contact.objects.get(user=user)
  661. object = Media.objects.get(id=pk)
  662. if not Product.objects.filter(contact=contact).filter(pk=object.product.pk).exists():
  663. raise Http404
  664. object.delete()
  665. return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
  666. def delete_video(request, pk):
  667. user = request.user
  668. contact = Contact.objects.get(user=user)
  669. object = Video.objects.get(id=pk)
  670. if not Product.objects.filter(contact=contact).filter(pk=object.product.pk).exists():
  671. raise Http404
  672. object.delete()
  673. return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))