views.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  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 ( product.raumangebot.max_length )
  222. #
  223. # print ( product.raumangebot.to_python() )
  224. if not years.__contains__(product.year):
  225. years.add(product.year)
  226. for country in product.country:
  227. if not used_countries.__contains__(country):
  228. used_countries.append(country)
  229. # if not used_orts.__contains__( product.get_ort_display() ):
  230. if not product.ort in orts:
  231. orts[product.ort] = product.get_ort_display()
  232. # print (product.raumangebot.get_list() )
  233. for raum in product.raumangebot:
  234. print(raum)
  235. # print(raum.get_display() )
  236. if not (raum in raum_agebote):
  237. raum_agebote[raum] = raum
  238. years.remove('')
  239. context['year_list'] = years
  240. context['count_list'] = used_countries
  241. context['frei_list'] = Product.FREI
  242. context['status_list'] = Product.STATUS
  243. context['ort_dict'] = orts
  244. context['raum_agebote_dict'] = raum_agebote
  245. context['altneu_list'] = Wohnprojekt.ALTNEU
  246. context['sponsor_cards'] = Template( config.SPONSOR_CARDS ).render( Context(context) )
  247. context['main_card'] = Template( config.MAIN_CARD ).render( Context(context) )
  248. context['textSearchForm'] = textSearchForm()
  249. return context
  250. # def get(self, request, *args, **kwargs):
  251. # print ("")
  252. template_name = 'marktplatz/product_overview.html'
  253. class SearchProductsView(ProductsView):
  254. def get_queryset(self, qfilter=None, **kwargs ):
  255. # original qs
  256. qs = super().get_queryset()
  257. self.user = self.request.user
  258. user = self.user
  259. if qfilter!=None:
  260. 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)
  261. qs = qs.order_by('frei')
  262. return qs.filter(public = True)
  263. def post(self, request, *args, **kwargs):
  264. qform = textSearchForm( request.POST )
  265. if qform.is_valid():
  266. self.object_list = self.get_queryset(qfilter= qform.cleaned_data["searchText"] )
  267. allow_empty = self.get_allow_empty()
  268. if not allow_empty:
  269. # When pagination is enabled and object_list is a queryset,
  270. # it's better to do a cheap query than to load the unpaginated
  271. # queryset in memory.
  272. if self.get_paginate_by(self.object_list) is not None and hasattr(self.object_list, 'exists'):
  273. is_empty = not self.object_list.exists()
  274. else:
  275. is_empty = not self.object_list
  276. if is_empty:
  277. raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.") % {
  278. 'class_name': self.__class__.__name__,
  279. })
  280. context = self.get_context_data()
  281. return self.render_to_response(context)
  282. class DetailView(generic.DetailView):
  283. model = Product
  284. template_name = 'marktplatz/product_detail.html'
  285. embed = False
  286. def get_context_data(self, **kwargs):
  287. # context = super().get_context_data(**kwargs)
  288. if self.embed :
  289. kwargs['embed'] = True
  290. # context['credits'] = Credit.objects.select_related().get(product = self.kwargs['pk'])
  291. # context['wohnprojekt'] = self.object.wohnprojekt
  292. return super().get_context_data(**kwargs)
  293. def post(self, request, *args, **kwargs):
  294. vote = int(request.POST['vote'])
  295. comment = str(request.POST['comment'])
  296. if vote <= 10:
  297. try:
  298. get_vote = Vote.objects.get(juryMember=self.request.user, product=self.kwargs['pk'])
  299. get_vote.vote = vote
  300. get_vote.comment = comment
  301. get_vote.save()
  302. except Vote.DoesNotExist:
  303. get_vote = Vote(product = Product.objects.get(pk=self.kwargs['pk']), juryMember= self.request.user, vote = vote, comment=comment)
  304. get_vote.save()
  305. else:
  306. return HttpResponseRedirect(request.path)
  307. return HttpResponseRedirect(reverse('products'))
  308. class CardDetailView(DetailView):
  309. template_name = 'marktplatz/product_detail_card.html'
  310. class AdminView(LoginRequiredMixin, generic.ListView):
  311. model = Product
  312. template_name='marktplatz/admin_panel.html'
  313. def get_context_data(self, **kwargs):
  314. context = super().get_context_data(**kwargs)
  315. return context
  316. def post(self, request, *args, **kwargs):
  317. # print (request.POST.dict())
  318. context = request.POST.dict()
  319. public = {k: v for k, v in context.items() if k.startswith('product_p')}
  320. for elemk in public:
  321. # print(elemk + " - " + public[elemk] )
  322. keys = elemk.split(".")
  323. current_product = Product.objects.get(pk=keys[1])
  324. if public[elemk] == 'true':
  325. current_product.public = True
  326. current_product.save()
  327. else:
  328. current_product.public = False
  329. current_product.save()
  330. edit = {k: v for k, v in context.items() if k.startswith('product_e')}
  331. # print (edit)
  332. for elemk in edit:
  333. # print(elemk + " - " + edit[elemk] )
  334. keys = elemk.split(".")
  335. current_product = Product.objects.get(pk=keys[1])
  336. if edit[elemk] == 'true':
  337. current_product.edit = True
  338. current_product.save()
  339. else:
  340. current_product.edit = False
  341. current_product.save()
  342. return HttpResponseRedirect('')
  343. class ProductsListView(generic.ListView):
  344. model = Product
  345. template_name='marktplatz/product_list.html'
  346. embed = False
  347. def get_context_data(self, **kwargs):
  348. if self.embed :
  349. kwargs['embed'] = True
  350. return super().get_context_data(**kwargs)
  351. def post(self, request, *args, **kwargs):
  352. # print (request.POST.dict())
  353. context = request.POST.dict()
  354. public = {k: v for k, v in context.items() if k.startswith('product_p')}
  355. for elemk in public:
  356. # print(elemk + " - " + public[elemk] )
  357. keys = elemk.split(".")
  358. current_product = Product.objects.get(pk=keys[1])
  359. if public[elemk] == 'true':
  360. current_product.public = True
  361. current_product.save()
  362. else:
  363. current_product.public = False
  364. current_product.save()
  365. edit = {k: v for k, v in context.items() if k.startswith('product_e')}
  366. # print (edit)
  367. for elemk in edit:
  368. # print(elemk + " - " + edit[elemk] )
  369. keys = elemk.split(".")
  370. current_product = Product.objects.get(pk=keys[1])
  371. if edit[elemk] == 'true':
  372. current_product.edit = True
  373. current_product.save()
  374. else:
  375. current_product.edit = False
  376. current_product.save()
  377. return HttpResponseRedirect('')
  378. class lightboximg(LoginRequiredMixin, TemplateView):
  379. template_name = "marktplatz/importold.html"
  380. def post(self, request):
  381. context = {'faild': ''}
  382. faild = ''
  383. from1 = int(request.POST['from'])
  384. to = int(request.POST['to'])
  385. products = Product.objects.all()
  386. i = 0
  387. for product in products:
  388. i+=1
  389. if (i < from1):
  390. continue
  391. if (i > to):
  392. break
  393. medias = product.media_set.all()
  394. for oldmedia in medias:
  395. if not oldmedia.image_norm:
  396. oldpic = oldmedia.image
  397. oldmedia.image_norm.save(oldmedia.filename() + '_norm', oldpic)
  398. oldmedia.save
  399. return render(request, self.template_name, context)
  400. def get(self, request):
  401. context = {'faild': ''}
  402. faild = ''
  403. context['faild'] = faild
  404. return render(request, self.template_name, context)
  405. class registerView(FormView):
  406. template_name = 'marktplatz/form.html'
  407. # form_class = RegisterForm
  408. def get(self, request):
  409. # form = self.form_class()
  410. context = request.GET.dict()
  411. context['form'] = RegisterForm
  412. context['signUp'] = SignUpForm
  413. return render(request, self.template_name, context)
  414. def post(self, request):
  415. # print ( request.POST.dict() )
  416. form = SignUpForm(request.POST)
  417. form_contact = RegisterForm(request.POST)
  418. #
  419. # Filter existing emails
  420. #
  421. qs = Contact.objects.filter( email=form_contact.data['email'] )
  422. if ( qs.count() ):
  423. form_contact.add_error('email', "Email already in use, please reset your password.")
  424. if form.is_valid() and form_contact.is_valid():
  425. # print (form.cleaned_data)
  426. # print (form_contact.cleaned_data)
  427. contact = form_contact.save(commit=False)
  428. user = form.save()
  429. user.email = contact.email
  430. user.first_name = contact.first_name
  431. user.last_name = contact.last_name
  432. user.set_password(form.cleaned_data.get('password1'))
  433. user.save()
  434. contact.user = user
  435. contact.save()
  436. username = form.cleaned_data.get('username')
  437. raw_password = form.cleaned_data.get('password1')
  438. group = Group.objects.get(name='submission')
  439. group.user_set.add(user)
  440. user = authenticate(username=username, password=raw_password)
  441. if user is not None:
  442. # A backend authenticated the credentials
  443. login(request, user)
  444. return redirect('products')
  445. else:
  446. # No backend authenticated the credentials
  447. send_mail(
  448. 'error with auth',
  449. 'Error in authorization.' + json.dumps( request.POST.dict() ),
  450. 'awards@berta.mediaarchitecture.org',
  451. ['juan@mediaarchitecture.org'],
  452. fail_silently=False,
  453. )
  454. return redirect('products')
  455. login(request, user)
  456. else:
  457. # print (form.errors)
  458. # print (form_contact.errors)
  459. send_mail(
  460. 'error with auth',
  461. '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),
  462. 'awards@berta.mediaarchitecture.org',
  463. ['juan@mediaarchitecture.org'],
  464. fail_silently=False,
  465. )
  466. context = request.POST.dict()
  467. context['signUp'] = form
  468. context['form'] = form_contact
  469. context['signup_errors'] = form.errors
  470. context['contact_errors'] = form_contact.errors
  471. return render(request, self.template_name, context)
  472. context = request.GET.dict()
  473. context['form'] = RegisterForm
  474. context['signUp'] = SignUpForm
  475. return render(request, self.template_name, context)
  476. class NewProductView(LoginRequiredMixin, FormView):
  477. use_ajax = True
  478. template_name = 'marktplatz/add.html'
  479. model = Product
  480. class NewWohnprojektView(LoginRequiredMixin, FormView):
  481. use_ajax = True
  482. template_name = 'marktplatz/add.html'
  483. model = Product
  484. def get(self, request,*args, **kwargs):
  485. # form = self.form_class()
  486. context = request.GET.dict()
  487. context['product'] = WohnprojektForm
  488. context['use_ajax'] = True
  489. context['info_txt'] = Template(config.INFO_TXT).render(Context(context))
  490. return render(request, self.template_name, context)
  491. def post(self, request):
  492. product_f = WohnprojektForm(request.POST, request.FILES)
  493. if product_f.is_valid():
  494. product = product_f.save(commit=False)
  495. product.contact = Contact.objects.get(user = self.request.user)
  496. product.edit=True
  497. product.public = False
  498. product.sumbitted = config.CURRENT_EVENT
  499. product.save()
  500. # product_f.save_m2m()
  501. if 'addImage' in request.POST:
  502. return HttpResponseRedirect(reverse('add-Image', kwargs={'pk': product.pk}))
  503. return HttpResponseRedirect(reverse('my-products'))
  504. else:
  505. context = request.POST.dict()
  506. context['product'] = product_f
  507. context['product_errors'] = product_f.errors
  508. context['use_ajax'] = True
  509. return render(request, self.template_name, context)
  510. class uploadView(LoginRequiredMixin, FormView):
  511. use_ajax = True
  512. template_name = 'marktplatz/file_upload.html'
  513. def get(self, request, pk):
  514. user = self.request.user
  515. contact = Contact.objects.get(user=user)
  516. if not Product.objects.filter(contact=contact).filter(pk=pk).exists():
  517. raise Http404
  518. product = Product.objects.get(pk=pk)
  519. photo = product.media_set.count()
  520. video = product.video_set.count()
  521. context = request.GET.dict()
  522. contact = Contact.objects.get(user=self.request.user)
  523. product = get_object_or_404(Wohnprojekt, (Q(pk=pk) & Q(contact=contact)))
  524. context['product'] = product
  525. context['images'] = Media.objects.filter(product=product)
  526. context['video'] = Video.objects.filter(product=product)
  527. context['media'] = MediaForm
  528. context['media_count'] = False
  529. context['video_count'] = False
  530. if photo >= 7:
  531. context['media_count'] = True
  532. if video >= 2:
  533. context['video_count'] = True
  534. context['use_ajax'] = True
  535. context['warning'] = False
  536. return render(request, self.template_name, context)
  537. def post(self, request, pk):
  538. vid1_f = MediaForm(request.POST, request.FILES)
  539. product = Product.objects.get(pk=pk)
  540. i = product.media_set.count()
  541. i += product.video_set.count()
  542. video = product.video_set.count()
  543. photo = product.media_set.count()
  544. context = request.GET.dict()
  545. contact = Contact.objects.get(user=self.request.user)
  546. product = get_object_or_404(Product, (Q(pk=pk) & Q(contact=contact)))
  547. context['product'] = product
  548. context['images'] = Media.objects.filter(product=product)
  549. context['video'] = Video.objects.filter(product=product)
  550. context['media'] = MediaForm
  551. context['media_count'] = False
  552. context['video_count'] = False
  553. context['use_ajax'] = True
  554. context['warning'] = False
  555. if vid1_f.is_valid():
  556. image = vid1_f.cleaned_data['image']
  557. name = image.name
  558. if 'png' in name or 'jpg' in name or 'jpeg' in name:
  559. if photo < 7:
  560. vid1 = Media()
  561. vid1.product = product
  562. vid1.filename = name
  563. vid1.copyright = vid1_f.cleaned_data['copyright']
  564. vid1.name_for = vid1_f.cleaned_data['name_for']
  565. vid1.image.save(name, image)
  566. vid1.image_small.save(str(i) + '_small', image)
  567. vid1.image_medium.save(str(i) + '_medium', image)
  568. vid1.image_big.save(str(i) + '_big', image)
  569. vid1.image_norm.save(str(i) + '_norm', image)
  570. vid1.save
  571. photo += 1
  572. else:
  573. context['warning'] = "You can not upload any more photos!"
  574. elif 'mp4' in name or 'm3u8' in name or 'm4v' in name:
  575. if video < 2:
  576. #TODO clean image here!
  577. vid1 = Video()
  578. vid1.product = product
  579. vid1.filename = name
  580. vid1.copyright = vid1_f.cleaned_data['copyright']
  581. vid1.name_for = vid1_f.cleaned_data['name_for']
  582. vid1.image.save(name, image)
  583. vid1.save
  584. video += 1
  585. else:
  586. context['warning'] = "You can not upload any more videos!"
  587. vid1_f.delete_temporary_files()
  588. if photo >= 7:
  589. context['media_count'] = True
  590. if video >= 2:
  591. context['video_count'] = True
  592. return render(request, self.template_name, context)
  593. handle_upload = FileFormUploader()
  594. class EditView(LoginRequiredMixin, FormView):
  595. template_name = 'marktplatz/add.html'
  596. def get(self, request, pk):
  597. user = self.request.user
  598. contact = Contact.objects.get(user=user)
  599. if not Product.objects.filter(contact=contact).filter(pk=pk).exists():
  600. raise Http404
  601. context = request.GET.dict()
  602. context['product'] = WohnprojektForm(instance=Wohnprojekt.objects.get(pk=pk))
  603. context['use_ajax'] = True
  604. context['info_txt'] = Template(config.INFO_TXT).render(Context(context))
  605. return render(request, self.template_name, context)
  606. def post(self, request, pk):
  607. product_f = WohnprojektForm(request.POST, request.FILES, instance=Wohnprojekt.objects.get(pk=pk))
  608. if product_f.is_valid():
  609. if product_f.has_changed():
  610. product = product_f.save( commit=False )
  611. update_fields = product_f.changed_data
  612. product.current_uri = request.build_absolute_uri( '/' ).rstrip('/')
  613. product.save( update_fields=update_fields )
  614. # product.save( )
  615. if 'addImage' in request.POST:
  616. return HttpResponseRedirect(reverse('add-Image', kwargs={'pk': pk}))
  617. return HttpResponseRedirect(reverse('my-products'))
  618. else:
  619. context = request.GET.dict()
  620. context['product'] = product_f
  621. context['product_errors'] = product_f.errors
  622. context['use_ajax'] = True
  623. return render(request, self.template_name, context)
  624. class UsersProducts(LoginRequiredMixin, generic.ListView):
  625. model = Product
  626. template_name='marktplatz/myProducts.html'
  627. def get_queryset(self):
  628. contact = Contact.objects.get(user=self.request.user)
  629. return Product.objects.filter(contact=contact)
  630. def get_context_data(self, **kwargs):
  631. context = super().get_context_data(**kwargs)
  632. contact = Contact.objects.get(user=self.request.user)
  633. context['user'] = self.request.user
  634. return context
  635. class MediaView(LoginRequiredMixin, TemplateView):
  636. template_name = 'marktplatz/media_overview.html'
  637. def get(self, request, pk):
  638. self.user = self.request.user
  639. user= self.user
  640. contact = Contact.objects.get(user=user)
  641. if not Product.objects.filter(contact=contact).filter(pk=pk).exists():
  642. raise Http404
  643. context = request.GET.dict()
  644. contact = Contact.objects.get(user=self.request.user)
  645. product = get_object_or_404(Product, (Q(pk = pk) & Q(contact = contact)))
  646. context['product'] = product
  647. context['media'] = Media.objects.filter(product=product)
  648. context['video'] = Video.objects.filter(product=product)
  649. return render(request, self.template_name, context)
  650. def delete_media(request, pk):
  651. user = request.user
  652. contact = Contact.objects.get(user=user)
  653. object = Media.objects.get(id=pk)
  654. if not Product.objects.filter(contact=contact).filter(pk=object.product.pk).exists():
  655. raise Http404
  656. object.delete()
  657. return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
  658. def delete_video(request, pk):
  659. user = request.user
  660. contact = Contact.objects.get(user=user)
  661. object = Video.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', '/'))