from django.shortcuts import render from django.views import generic from django.views.generic import TemplateView from .models import Product, Credit, Description, Vote, Contact, Interaction, Media, Video, Link, Category from django.db import models from django.contrib.auth.models import User from django.contrib.auth.mixins import LoginRequiredMixin from django.core import serializers from django.core.mail import send_mail from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User, Group from django.http import HttpResponseRedirect from django.urls import reverse from django.core.files import File from django.http import HttpResponse from django.views.generic import FormView from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from django.forms import formset_factory from django.forms import BaseModelFormSet from django.forms import modelformset_factory, inlineformset_factory from .forms import LinkFormSet, LinkForm, FormsetHelper, MediaFormsetHelper, MediaFormSet from django.contrib import messages from django_file_form.uploader import FileFormUploader from django_countries import countries from django.template import Context, Template from django.conf import settings from constance import config from django.http import Http404 from django.db.models import Count from PIL import Image from PIL import ImageFont from PIL import ImageDraw from django.db.models import Q from django.shortcuts import get_list_or_404, get_object_or_404 from .forms import RegisterForm, SignUpForm, DescriptionForm,SubmissionForm,CreditForm,DescriptionForm,InteractionForm,LinkForm,MediaForm,VideoForm, MediaForm_test, MediaForm1, MediaForm2 import os import itertools from PIL import Image import json import copy import csv # Create your views here. def index(request): context = {} return render(request, 'index.html', context = context) def about(request): context = {} context = {'about_text': Template(config.ABOUT_CONTENT).render(Context(context))} return render(request, 'marktplatz/about.html', context) #template = Template( config.ABOUT_CONTENT ) #return HttpResponse( template.render( Context(context) ) ) #return render(request, rendered , context = context) def submit(request): context = {} context = {'submit_text': Template(config.SUBMIT_TEXT).render(Context(context))} return render(request,'marktplatz/submit.html', context) def error_404_view(request, exception): data = {"name": "ThePythonDjango.com"} return render(request,'marktplatz/error_404.html', data) @login_required def home(request): user = request.user if user.groups.filter(name='submission').exists(): return HttpResponseRedirect(reverse('MyProducts')) else: return HttpResponseRedirect(reverse('Products')) class ProductsView(generic.ListView): model = Product #context_object_name = 'Products' # show the best 4 website finish def get_queryset(self): # original qs qs = super().get_queryset() self.user = self.request.user user = self.user if user.groups.filter(name='jury').exists(): return qs.filter(sumbitted = config.CURRENT_EVENT) if user.groups.filter(name='submission').exists(): contact = Contact.objects.get(user=user) return qs.filter(contact = contact) if user.is_superuser: return qs return qs.filter(public = True) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user =self.request.user context['user'] = user used_countries = [] years = {''} for Product in context['product_list']: if not years.__contains__(Product.year): years.add(Product.year) for country in Product.country: if not used_countries.__contains__(country): used_countries.append(country) years.remove('') context['year_list'] = years context['count_list'] = used_countries context['cat_list'] = Category.objects.all context['sponsor_cards'] = Template( config.SPONSOR_CARDS ).render( Context(context) ) context['main_card'] = Template( config.MAIN_CARD ).render( Context(context) ) return context template_name = 'marktplatz/product_overview.html' class DetailView(generic.DetailView): model = Product template_name = 'marktplatz/Product_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['credits'] = Credit.objects.select_related().get(Product = self.kwargs['pk']) context['descriptions'] = Description.objects.select_related().get(Product = self.kwargs['pk']) context['interactions'] = Interaction.objects.select_related().get(Product=self.kwargs['pk']) context['PAUI'] = Category.objects.get(short_name='PAUI') return context def post(self, request, *args, **kwargs): vote = int(request.POST['vote']) comment = str(request.POST['comment']) if vote <= 10: try: get_vote = Vote.objects.get(juryMember=self.request.user, Product=self.kwargs['pk']) get_vote.vote = vote get_vote.comment = comment get_vote.save() except Vote.DoesNotExist: get_vote = Vote(Product = Product.objects.get(pk=self.kwargs['pk']), juryMember= self.request.user, vote = vote, comment=comment) get_vote.save() else: return HttpResponseRedirect(request.path) return HttpResponseRedirect(reverse('Products')) class VoteView(LoginRequiredMixin, generic.ListView): model = Product template_name='marktplatz/voteDetail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['user'] = User.objects.filter(groups__name='JuryMembers') return context class CidView(LoginRequiredMixin, generic.ListView): model = Product template_name='marktplatz/votes_cid.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context def post(self, request, *args, **kwargs): for pk in request.POST.dict(): if not 'csrfmiddlewaretoken' in pk: if request.POST[pk] != '' and ('cid' in pk): now_Product = Product.objects.get(pk=pk.split('.')[0]) now_Product.class_cid = request.POST[pk] now_Product.save() if request.POST[pk] != '' and ('sub' in pk): now_Product = Product.objects.get(pk=pk.split('.')[0]) now_Product.sumbitted = request.POST[pk] now_Product.save() return HttpResponseRedirect('') class AdminView(LoginRequiredMixin, generic.ListView): model = Product template_name='marktplatz/admin_panel.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context def post(self, request, *args, **kwargs): for pk in request.POST.dict(): print(pk) print("test") if not 'csrfmiddlewaretoken' in pk: if request.POST[pk] != '' and ('public' in pk): pass #now_Product = Product.objects.get(pk=pk.split('.')[0]) #now_Product.public = request.POST[pk].checktest #now_Product.save() if request.POST[pk] != '' and ('edit' in pk): pass #now_Product = Product.objects.get(pk=pk.split('.')[0]) #now_Product.edit = request.POST[pk].checktest #now_Product.save() return HttpResponseRedirect('') class importOldProducts(LoginRequiredMixin, TemplateView): template_name = "marktplatz/importold.html" def post(self, request): importPath = settings.IMPORT_PATH filepath = importPath+'results-survey961137.csv' context= {'faild':''} faild='Log: \n' from1 =int(request.POST['from']) to =int(request.POST['to']) with open(filepath, newline='', encoding='utf8') as csvfile: 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:'] reader = csv.DictReader(csvfile, delimiter=';',fieldnames=fieldnames) reader.__next__() counter = 0; while(counter< from1): reader.__next__() counter += 1 for row in reader: if(counter > to): break counter+=1 Product = Product() #4 the contact contact = Contact() contact.first_name =row['Name [First name]'] contact.last_name =row['Name [Last name]'] contact.adress =row['Address [Street number & name]'] contact.postcode =row['Address [Postcode]'] contact.city =row['Address [City]'] contact.country =row['Address [Country]'] contact.email =row['Email address'] contact.phonenumber =row['Phone Number'] contact.skype_name =row['Skype name'] contact.website =row['Website'] contact.alternate_phonenumber =row['Alternate phone number'] contact.save() credit = Credit() credit.owner =row['Credits [Building or Product owner]'] credit.architecture =row['Credits [Architecture]'] credit.concept =row['Credits [Product artist/concept/design/planning]'] credit.structural_engeneering =row['Credits [Structural engineering]'] credit.facade_design =row['Credits [Facade design]'] credit.face_construction =row['Credits [Facade construction]'] credit.kinetic_design =row['Credits [Kinetic engineering]'] credit.light_design =row['Credits [Light design]'] credit.tecnical_layout =row['Credits [Technical layout light (LED technical layout)]'] credit.display_content =row['Credits [Display content/ visuals/ showreel]'] credit.light_hardware =row['Credits [Light hardware (LED hardware)]'] credit.lightning_software =row['Credits [Lighting control software]'] credit.Product_coordination =row['Credits [Product co-ordination]'] credit.membrane_skin =row['Credits [Membrane skin]'] credit.interaction_design =row['Credits [Interaction design/ programming]'] credit.sponsor =row['Credits [Product sponsor/ support]'] #Credits [Pixel or other basic module/ elements] credit.save() interaction = Interaction() interaction.communtity =row['Community or communities involved'] interaction.host =row['Host organization'] interaction.legal_form =row['Legal form'] interaction.issues =row['Issues addressed'] interaction.impact =row['Impact'] interaction.tools =row['Tools developed'] interaction.tools_used =row['Tools used'] interaction.next_steps =row['Next steps'] interaction.save() description = Description() description.facade =row['Facade type and geometry (structure)'] description.light_creation =row['Kind of light creation'] description.resolution =row['Resolution and transmitting behaviour'] description.pixel_distance =row['Pixel distance'] #description.luminance ='' description.urban_situation =row['Urban situation'] description.description_showreel =row['Description of showreel'] description.save() Product.title=row['Product title'] Product.country = row['Country'] Product.city = row['City'] Product.year = row['Year of completion'] Product.owner= row['Credits [Building or Product owner]'] Product.teaser_txt = row['Teaser text'] Product.header = row['Description (header)'] Product.description_txt = row['Description (long text)'] Product.interaction = interaction Product.credits = credit Product.description=description Product.contact = contact Product.cid=1 Product.class_cid='1' Product.save() AA = Category.objects.get(short_name = 'AA') FP = Category.objects.get(short_name='FP') MA = Category.objects.get(short_name='MA') SMA = Category.objects.get(short_name='SMA') PAUI = Category.objects.get(short_name='PAUI') if 'Yes' in row['In the following categories [Animated architecture]']: Product.category.add(AA) if 'Yes' in row['In the following categories [Future trends & prototypes]']: Product.category.add(FP) if 'Yes' in row['In the following categories [Money architecture]']: Product.category.add(MA) if 'Yes' in row['In the following categories [Spatial media art]']: Product.category.add(SMA) if 'Yes' in row['In the following categories [Participatory architecture & urban interaction]']: Product.category.add(PAUI) Product.save() def readMedia(number): mediadetail = json.loads(row['Picture of the Product' + str(number)])[0] if 'mp4' in mediadetail['ext']: media = Video() elif 'png' in mediadetail['ext'] or 'jpg' in mediadetail['ext'] or 'png' in mediadetail['ext']: media = Media() else: return row['Product title']+' : '+ str(mediadetail) +' FILEERROR'+ '\n' media.Product = Product media.name_for = mediadetail['title'] media.filename = row['Product title'] + str(number) media.copyright = row['Credit' + str(number)] file = open(importPath+mediadetail['filename'], 'rb') image = File(file) media.image.save(str(number) + '.' + mediadetail['ext'], image) if 'png' in mediadetail['ext'] or 'jpg' in mediadetail['ext'] or 'png' in mediadetail['ext']: media.image_small.save(str(number) + '_small' + '.' + mediadetail['ext'], image) media.image_medium.save(str(number) + '_medium' + '.' + mediadetail['ext'], image) media.image_big.save(str(number) + '_big' + '.' + mediadetail['ext'], image) media.image_norm.save(str(number) + '_norm' + '.' + mediadetail['ext'], image) media.save return row['Product title'] + str(mediadetail) + ' mediasucsess' + '\n' if row['filecount0'] == '1' : faild +=readMedia(0) if row['filecount1'] == '1': faild +=readMedia(1) if row['filecount2'] == '1': faild +=readMedia(2) if row['filecount3'] == '1': faild +=readMedia(3) if row['filecount4'] == '1': faild +=readMedia(4) if row['filecount5'] == '1': faild +=readMedia(5) if row['Link'] != '': Link.objects.create(Product=Product, link= row['Link']) if row['Other links [Link 1]'] != '': Link.objects.create(Product=Product, link=row['Other links [Link 1]']) if row['Other links [Link 2]'] != '': Link.objects.create(Product=Product, link=row['Other links [Link 2]']) if row['Other links [Link 3]'] != '': Link.objects.create(Product=Product, link=row['Other links [Link 3]']) faild += row['Product title'] + ' Productsuccsess' + '\n' context['faild'] = faild print(faild) return render(request, self.template_name, context) def get(self, request): context = {'faild': ''} faild='' context['faild'] = faild return render(request, self.template_name, context ) class importOldJson(LoginRequiredMixin, TemplateView): template_name = "marktplatz/importold.html" def post(self, request): context = {'faild': ''} faild= '' from1 = int(request.POST['from']) to = int(request.POST['to']) def parseData(key, value,faild, ProductInst, creditInst, descriptionInst,interactionInst, cid): print('{!r} : {!r}'.format(key, value)) if "Country" == key: ProductInst.country = value elif "City" == key: ProductInst.city = value elif "Year" == key: if isinstance(value,int): ProductInst.year = value elif "Owner" in key: ProductInst.owner = value creditInst.owner = value elif "Architect" in key: creditInst.architecture = value elif "Light Design" in key: creditInst.light_design = value elif "Lighting Control Software" in key: creditInst.lightning_software = value elif "Lighting Control Hardware" in key: creditInst.light_hardware = value elif "Technical Layout" in key: creditInst.technical_layout = value elif "Programming, Interaction Design" == key: creditInst.interaction_design = value elif "Product Coordination" == key: creditInst.Product_coordination = value elif "Façade Design" == key: creditInst.facade_design = value elif "Kind of Light Creation" == key: descriptionInst.light_creation = value elif "Resolution and Transmitting" in key: descriptionInst.resolution = value elif "Luminance" in key: descriptionInst.luminance = value elif "Urban Situation" == key: descriptionInst.urban_situation = value elif "cid" == key: ProductInst.class_cid = value cid = value elif "heading" == key: ProductInst.title = value elif "teaser" == key: ProductInst.teaser_txt= value elif "title" == key: ProductInst.header = value elif "description" == key: ProductInst.description_txt = value elif "Pixel Distance" in key: descriptionInst.pixel_distance = value elif "category" == key: ProductInst.save() if "Animated Architecture" in value: ProductInst.category.add(Category.objects.get(short_name='AA')) if "Spatial Media Art" in value: ProductInst.category.add(Category.objects.get(short_name='SMA')) if "Money Architecture" in value: ProductInst.category.add(Category.objects.get(short_name='MA')) if "Participatory Architecture" in value: ProductInst.category.add(Category.objects.get(short_name='PAUI')) if "Future Trends" in value: ProductInst.category.add(Category.objects.get(short_name='FP')) elif 'Façade Type and Geometry' in key: descriptionInst.facade = value elif "Product Artist/Concept/Planning" in key: creditInst.concept = value elif "Artist" in key: creditInst.concept = value elif "support" in key: creditInst.sponsor = value elif "Structural Engineering" in key: creditInst.structural_engeneering = value elif "LED" in key: creditInst.light_hardware = value elif "Showreel" in key: descriptionInst.description_showreel = value elif "Photo Credits" in key: ProductInst.photo = value elif "Video Credits" in key: ProductInst.videocts = value elif "Link 1" in key: ProductInst.save() Link.objects.create(Product=ProductInst, link=value) elif "Link 2" in key: ProductInst.save() Link.objects.create(Product=ProductInst, link=value) elif "Link 3" in key: ProductInst.save() Link.objects.create(Product=ProductInst, link=value) elif "Link 4" in key: ProductInst.save() Link.objects.create(Product=ProductInst, link=value) elif "Programming, Interaction Design" in key: creditInst.interaction_design = value elif "tables" == key: iterate_list(value, faild, ProductInst, creditInst, descriptionInst, interactionInst, cid) elif "files" == key: ProductInst.save() for file in value: print('!!!!!!!!!!!!!!!!!!!'+file) fileimg='' if 'mp4' in file or 'm3u8' in file or 'm4v' in file: media = Video() try: fileimg = open(settings.OLD_IMPORT_PATH + cid + '/' + file.split('.')[0]+'.mp4', 'rb') except: try: fileimg = open(settings.OLD_IMPORT_PATH + cid + '/' + file.split('.')[0]+'.m4v', 'rb') except: fileimg = open(settings.OLD_IMPORT_PATH + cid + '/' + file.split('.')[0]+'.m3u8', 'rb') elif 'png' in file or 'jpg' in file or 'png' in file: media = Media() fileimg = open(settings.OLD_IMPORT_PATH + cid + '/' + file, 'rb') media.Product = ProductInst media.filename = file image = File(fileimg) media.image.save(file, image) if 'png' in file or 'jpg' in file or 'png' in file: media.image_small.save(file.split('.')[0]+'_small', image) media.image_medium.save(file.split('.')[0]+'_medium', image) media.image_big.save(file.split('.')[0] +'_big', image) media.image_norm.save(file.split('.')[0] + '_norm', image) media.save return cid def iterate_rec(dictionary, faild, ProductInst, creditInst, descriptionInst, interactionInst, cid): for key, value in dictionary.items(): if isinstance(value, dict): cid =iterate_rec(value, faild, ProductInst, creditInst, descriptionInst, interactionInst, cid) else: cid = parseData(key, value,faild, ProductInst, creditInst, descriptionInst,interactionInst, cid) ProductInst.save return cid def iterate_list(dictionary, faild, ProductInst, creditInst, descriptionInst, interactionInst, cid): for item in dictionary: if item == None: return cid = iterate_rec(item,faild, ProductInst, creditInst, descriptionInst,interactionInst, cid) ProductInst.save return cid def all_files(directory): for path, files, dirs in os.walk(directory): for f in dirs: yield os.path.join(path, f) olfolder = settings.OLD_IMPORT_PATH iter1= all_files(olfolder) alljason = [f for f in iter1 if f.endswith('.json')] i=0 for filepath in alljason: i+=1 print(filepath, i) if(ito): break print(filepath) faild += filepath +'\n' ProductInst = Product() creditInst = Credit() descriptionInst = Description() interactionInst = Interaction() with open(filepath, encoding='utf8') as data_file: data_file_str = data_file.read() data_file_json = json.loads(data_file_str) print ( filepath.split('/') ) cid = filepath.split('/')[5] iterate_rec(data_file_json, faild, ProductInst, creditInst, descriptionInst,interactionInst, cid) ProductInst.submitted = 'old' creditInst.save() descriptionInst.save() interactionInst.save() ProductInst.credits =creditInst ProductInst.description=descriptionInst ProductInst.interaction = interactionInst ProductInst.save() context['faild'] = faild return render(request, self.template_name, context) def get(self, request): template_name = "marktplatz/importold.html" context = {'faild': ''} faild = '' context['faild'] = faild return render(request, self.template_name, context) class lightboximg(LoginRequiredMixin, TemplateView): template_name = "marktplatz/importold.html" def post(self, request): context = {'faild': ''} faild = '' from1 = int(request.POST['from']) to = int(request.POST['to']) Products = Product.objects.all() i = 0 for Product in Products: i+=1 if (i < from1): continue if (i > to): break medias = Product.media_set.all() for oldmedia in medias: if not oldmedia.image_norm: oldpic = oldmedia.image oldmedia.image_norm.save(oldmedia.filename() + '_norm', oldpic) oldmedia.save return render(request, self.template_name, context) def get(self, request): context = {'faild': ''} faild = '' context['faild'] = faild return render(request, self.template_name, context) class registerView(FormView): template_name = 'marktplatz/form.html' #form_class = RegisterForm def get(self, request): #form = self.form_class() context = request.GET.dict() context['form'] = RegisterForm context['signUp'] = SignUpForm return render(request, self.template_name, context) def post(self, request): print ( request.POST.dict() ) form = SignUpForm(request.POST) form_contact = RegisterForm(request.POST) # # Filter existing emails # qs = Contact.objects.filter( email=form_contact.data['email'] ) if ( qs.count() ): form_contact.add_error('email', "Email already in use, please reset your password.") if form.is_valid() and form_contact.is_valid(): print (form.cleaned_data) print (form_contact.cleaned_data) contact = form_contact.save(commit=False) user = form.save() user.email = contact.email user.first_name = contact.first_name user.last_name = contact.last_name user.set_password(form.cleaned_data.get('password1')) user.save() contact.user = user contact.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') group = Group.objects.get(name='submission') group.user_set.add(user) user = authenticate(username=username, password=raw_password) if user is not None: # A backend authenticated the credentials login(request, user) return redirect('Products') else: # No backend authenticated the credentials send_mail( 'error with auth', 'Error in authorization.' + json.dumps( request.POST.dict() ), 'awards@berta.mediaarchitecture.org', ['juan@mediaarchitecture.org'], fail_silently=False, ) return redirect('Products') login(request, user) else: print (form.errors) print (form_contact.errors) send_mail( 'error with auth', '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), 'awards@berta.mediaarchitecture.org', ['juan@mediaarchitecture.org'], fail_silently=False, ) context = request.POST.dict() context['signUp'] = form context['form'] = form_contact context['signup_errors'] = form.errors context['contact_errors'] = form_contact.errors return render(request, self.template_name, context) # if form_contact.is_valid(): # contact = form_contact.save(commit=False) # contact.user = user # contact.save() # # return redirect('Products') context = request.GET.dict() context['form'] = RegisterForm context['signUp'] = SignUpForm return render(request, self.template_name, context) class NewSubmitView(LoginRequiredMixin, FormView): use_ajax = True template_name = 'marktplatz/add.html' #model = Product def get(self, request,*args, **kwargs): # form = self.form_class() context = request.GET.dict() context['Product'] = SubmissionForm context['credits'] = CreditForm context['description'] = DescriptionForm context['interaction'] = InteractionForm context['lnks'] = LinkFormSet context['lnks_helper'] = FormsetHelper() context['use_ajax'] = True context['info_txt'] = Template(config.INFO_TXT).render(Context(context)) return render(request, self.template_name, context) def post(self, request): Product_f = SubmissionForm(request.POST, request.FILES) credits_f = CreditForm(request.POST) description_f = DescriptionForm(request.POST) interaction_f = InteractionForm(request.POST) lnks_f = LinkFormSet(request.POST) vid1_f = VideoForm(request.POST, request.FILES) if Product_f.is_valid(): Product = Product_f.save(commit=False) credits = credits_f.save(commit=False) description =description_f.save(commit=False) interaction =interaction_f.save(commit=False) credits.save() description.save() interaction.save() Product.credits = credits Product.description = description Product.interaction = interaction Product.contact = Contact.objects.get(user = self.request.user) Product.edit=True Product.public = False Product.sumbitted = config.CURRENT_EVENT Product.save() Product_f.save_m2m() for lnk in lnks_f: if lnk.is_valid(): lnk_ = lnk.save(commit=False) lnk_.Product=Product lnk_.save() if 'addImage' in request.POST: return HttpResponseRedirect(reverse('add-Image', kwargs={'pk': Product.pk})) return HttpResponseRedirect(reverse('MyProducts')) else: context = request.POST.dict() context['Product'] = Product_f context['credits'] = credits_f context['description'] = description_f context['interaction'] = interaction_f context['lnks'] = lnks_f context['lnks_helper'] = FormsetHelper() context['use_ajax'] = True return render(request, self.template_name, context) class uploadView(LoginRequiredMixin, FormView): use_ajax = True template_name = 'marktplatz/file_upload.html' def get(self, request, pk): user = self.request.user contact = Contact.objects.get(user=user) if not Product.objects.filter(contact=contact).filter(pk=pk).exists(): raise Http404 Product = Product.objects.get(pk=pk) photo = Product.media_set.count() video = Product.video_set.count() context = request.GET.dict() contact = Contact.objects.get(user=self.request.user) Product = get_object_or_404(Product, (Q(pk=pk) & Q(contact=contact))) context['Product'] = Product context['images'] = Media.objects.filter(Product=Product) context['video'] = Video.objects.filter(Product=Product) context['media'] = MediaForm context['media_count'] = False context['video_count'] = False if photo >= 7: context['media_count'] = True if video >= 2: context['video_count'] = True context['use_ajax'] = True context['warning'] = False return render(request, self.template_name, context) def post(self, request, pk): vid1_f = MediaForm(request.POST, request.FILES) Product = Product.objects.get(pk=pk) i = Product.media_set.count() i += Product.video_set.count() video = Product.video_set.count() photo = Product.media_set.count() context = request.GET.dict() contact = Contact.objects.get(user=self.request.user) Product = get_object_or_404(Product, (Q(pk=pk) & Q(contact=contact))) context['Product'] = Product context['images'] = Media.objects.filter(Product=Product) context['video'] = Video.objects.filter(Product=Product) context['media'] = MediaForm context['media_count'] = False context['video_count'] = False context['use_ajax'] = True context['warning'] = False if vid1_f.is_valid(): image = vid1_f.cleaned_data['image'] name = image.name if 'png' in name or 'jpg' in name or 'jpeg' in name: if photo < 7: vid1 = Media() vid1.Product = Product vid1.filename = name vid1.copyright = vid1_f.cleaned_data['copyright'] vid1.name_for = vid1_f.cleaned_data['name_for'] vid1.image.save(name, image) vid1.image_small.save(str(i) + '_small', image) vid1.image_medium.save(str(i) + '_medium', image) vid1.image_big.save(str(i) + '_big', image) vid1.image_norm.save(str(i) + '_norm', image) vid1.save photo += 1 else: context['warning'] = "You can not upload any more photos!" elif 'mp4' in name or 'm3u8' in name or 'm4v' in name: if video < 2: #TODO clean image here! vid1 = Video() vid1.Product = Product vid1.filename = name vid1.copyright = vid1_f.cleaned_data['copyright'] vid1.name_for = vid1_f.cleaned_data['name_for'] vid1.image.save(name, image) vid1.save video += 1 else: context['warning'] = "You can not upload any more videos!" vid1_f.delete_temporary_files() if photo >= 7: context['media_count'] = True if video >= 2: context['video_count'] = True return render(request, self.template_name, context) handle_upload = FileFormUploader() class EditView(FormView): template_name = 'marktplatz/add.html' def get(self, request, pk): user = self.request.user contact = Contact.objects.get(user=user) if not Product.objects.filter(contact=contact).filter(pk=pk).exists(): raise Http404 context = request.GET.dict() context['Product'] = SubmissionForm(instance=Product.objects.get(pk=pk)) context['credits'] = CreditForm(instance = Credit.objects.select_related().get(Product=pk)) context['description'] = DescriptionForm(instance = Description.objects.select_related().get(Product=pk)) context['interaction'] = InteractionForm(instance = Interaction.objects.select_related().get(Product=pk)) linkFormSet = inlineformset_factory(Product,Link, form=LinkForm, extra=0) myLinkFormSet = linkFormSet(instance= Product.objects.get(pk=pk) ) context['lnks'] = myLinkFormSet context['lnks_helper'] = FormsetHelper() context['use_ajax'] = True context['info_txt'] = Template(config.INFO_TXT).render(Context(context)) return render(request, self.template_name, context) def post(self, request, pk): Product_f = SubmissionForm(request.POST, request.FILES, instance=Product.objects.get(pk=pk)) credits_f = CreditForm(request.POST,instance = Credit.objects.select_related().get(Product=pk)) description_f = DescriptionForm(request.POST,instance = Description.objects.select_related().get(Product=pk)) lnks_f = LinkFormSet(request.POST,instance = Product.objects.get(pk=pk) ) interaction_f = InteractionForm(request.POST,instance = Interaction.objects.select_related().get(Product=pk)) vid1_f = VideoForm(request.POST, request.FILES) if Product_f.is_valid(): if Product_f.has_changed(): Product_f.save() if credits_f.has_changed() : credits_f.save() if description_f.has_changed() : description_f.save() if interaction_f.has_changed(): interaction_f.save() Product = Product_f.save() for lnk in lnks_f: if lnk.is_valid(): lnk_ = lnk.save(commit=False) lnk_.Product = Product lnk_.save() if 'addImage' in request.POST: return HttpResponseRedirect(reverse('add-Image', kwargs={'pk': pk})) return HttpResponseRedirect(reverse('MyProducts')) else: context = request.GET.dict() context['Product'] = Product_f context['credits'] = credits_f context['description'] = description_f context['interaction'] = interaction_f context['lnks'] = lnks_f context['lnks_helper'] = FormsetHelper() context['use_ajax'] = True return render(request, self.template_name, context) class UsersProducts(LoginRequiredMixin, generic.ListView): model = Product template_name='marktplatz/myProducts.html' def get_queryset(self): contact =Contact.objects.get(user=self.request.user) return Product.objects.filter(contact=contact) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) contact = Contact.objects.get(user=self.request.user) context['user'] = self.request.user return context class MediaView(LoginRequiredMixin, TemplateView): template_name = 'marktplatz/media_overview.html' def get(self, request, pk): self.user = self.request.user user= self.user contact = Contact.objects.get(user=user) if not Product.objects.filter(contact=contact).filter(pk=pk).exists(): raise Http404 context = request.GET.dict() contact = Contact.objects.get(user=self.request.user) Product = get_object_or_404(Product, (Q(pk = pk) & Q(contact = contact))) context['Product'] = Product context['media'] = Media.objects.filter(Product=Product) context['video'] = Video.objects.filter(Product=Product) return render(request, self.template_name, context) def delete_media(request, pk): user = request.user contact = Contact.objects.get(user=user) object = Media.objects.get(id=pk) if not Product.objects.filter(contact=contact).filter(pk=object.Product.pk).exists(): raise Http404 object.delete() return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) def delete_video(request, pk): user = request.user contact = Contact.objects.get(user=user) object = Video.objects.get(id=pk) if not Product.objects.filter(contact=contact).filter(pk=object.Product.pk).exists(): raise Http404 object.delete() return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) #class datetimeadd(LoginRequiredMixin, TemplateView): # # template_name = "marktplatz/importold.html" # # def post(self, request): # context = {'faild': ''} # faild = '' # from1 = int(request.POST['from']) # to = int(request.POST['to']) # # Products = Product.objects.all() # i = 0 # # for Product in Products: # i += 1 # if (i < from1): # continue # if (i > to): # break # # if Product.date_submitted > # # return render(request, self.template_name, context) # # def get(self, request): # context = {'faild': ''} # faild = '' # context['faild'] = faild # # return render(request, self.template_name, context)