Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hosting HTML+CSS+JS websites with Django rest framework backend
My backend APIs are hosted on Django rest framework and the for the frontend I have purchased a theme which is on HTML, CSS, Bootstrap, and Javascript, I wanted to know what would be the best practice to host this website in production, should I have two servers one for handling the static website and other for the backend or shall I integrate this with the backend. The theme is quite vast and would like to go with the first option, so I go with the first option then where should I host the website, and does it impact the performance? I have already researched but could not find what would be the best practice in this situation, Let me know if any other details are required. -
Locally hosted Django project for long-term use in local network
I am currently implementing a Django web application, which will be used only locally but long-term. I already managed to start the Django server on my local machine using python manage 0.0.0.0:myport and I am able to connect from any mobile device using MyLocalIPv4:myport. In best case I only want to start the Django server once, establish a connection between a mobile device and the web app and let the web app run for an undefined long time on that mobile device Now my assumption is, that MyLocalIPv4 will be changing over time as it is a dynamic IP address, which will force the user (or even worse myself) to look up the new IP address and re-establish the connection. My question are: Do you know any mechanisms on how I can avoid this type of behaviour using another (maybe static) referral to the web app ? What do you think about this web application in term of security issues ? -
Ordering a filter result in Django
I made a Search results function in view.py: def search_results(request): book_list = Book.objects.all() book_filter = BookFilter(request.GET, queryset=book_list) book_list = book_filter.qs.order_by('title') return render(request, 'catalog/search_results.html', {'filter': book_list}) But it seems that the line book_list = book_filter.qs.order_by('title') doesn't have any effect on the result. Could someone help? -
Unable to import test module in Django 3
I'm trying to run tests for my app as described in the Django documentation: https://docs.djangoproject.com/en/3.0/intro/tutorial05/ However, with the minimal example I have shown below, I get an error complaining that: RuntimeError: Model class myproject.myapp.models.MyModel doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Is there some extra configuration I need to make to enable running of tests, or some other mistake that I may have done or forgotten? Full stacktrace: $ ./manage.py test myapp System check identified no issues (0 silenced). E ====================================================================== ERROR: myproject.myapp.tests (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: myproject.myapp.tests Traceback (most recent call last): File "/usr/lib64/python3.8/unittest/loader.py", line 436, in _find_test_path module = self._get_module_from_name(name) File "/usr/lib64/python3.8/unittest/loader.py", line 377, in _get_module_from_name __import__(name) File "/home/simernes/workspace/myproject/myapp/tests.py", line 2, in <module> from .models import MyModel File "/home/simernes/workspace/myproject/myapp/models.py", line 5, in <module> class MyModel(models.Model): File "/home/simernes/workspace/myproject/env/lib/python3.8/site-packages/django/db/models/base.py", line 112, in __new__ raise RuntimeError( RuntimeError: Model class myproject.myapp.models.MyModel doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. settings.py: INSTALLED_APPS = [ 'myapp.apps.MyAppConfig', ... ] apps.py: from django.apps import AppConfig class MyAppConfig(AppConfig): name = 'myapp' tests.py: from django.test import TestCase from .models import MyModel # Create your tests here. class MyModelTests(TestCase): def model_names_are_unique(self): """ The database crashes if … -
Django + NGINX Protecting Media Links using X-Accel-redirect not working
I am trying to get the image links delivered via Django Views to undergo additional security checks so that only the person with the correct permission can access the link. Currently, this is the setup: an User X uploads a photo from his account. The files get saved in media/images/ folder. And the django CreateView redirects to 'view/<id_of_image_in_db>' --> Which triggers Django Detailview function . class PhotosHDView(DetailView): model = MYPhotos template_name = 'detail.html' context_object_name = 'photos' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['userName'] = self.request.user return context The detail.html gets the photos object and renders in card. {% block content %} <div class="container mx-auto"> <div class="card "> <img src="{{photos.image.url}}" class="card-img-top" alt="..."> </div> </div> {% endblock %} When the page is rendered "{{photos.image.url}}" will be /media/images/<image_name> This all works fine in production with NGINX with the default method where the images are served by NGINX without communicating with Django server. Working NGINX Config: location /media/ { autoindex off; alias /home/ubuntu/photoApp/media/; } Now if you right-click the image and get the image URL rendered in detail view and go to an incog window and paste the link, the image will be displayed irrespective of who is accessing it. Because there is no … -
Verify database integrity using Django
There is a complex app with the back-end powered by Django. It contains many-to-one many-to-many and https://django-polymorphic.readthedocs.io/en/stable/. Using Django migration for updating database models. Problem A very complex migration for the existing database fails. There Foreign Key constraint related problems similar to: ERROR: insert or update on table "foo" violates foreign key constraint "D286496390ec910156ccc566ec44e73f" DETAIL: Key (bar_id)=(123) is not present in table "bar". So in other words there is a record which references a non-existing record in the database. Question Is it possible to somehow use Django to iterate over each object in the database and validate it contains no "broken" records (referencing non-existent records)? -
Heroku django deployment 500error when DEBUG=False
It appears that im getting a 500 error when i set DEBUG=False and i have tried also to add in ALLOWED_HOSTS= ['*'] and ['.herokuapp.com'] but still doesnt work.. It seems that is a very popular error but i have tried couple solutions and honestly i havent figure out anything. There is a suggestion to enable logging found here : Heroku server error (500) when Debug = False , whitenoise could not find style.css LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), }, }, } but doesnt show anything more in heroku logs --tail -
While using Ajax model object are not being saved
I have a model which is defined as follows in models.py class Comments(models.Model): Post_Name = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='Comments_Post_Name') Comment_By = models.ForeignKey(User, on_delete=models.CASCADE, related_name='Comment_By') Comment = models.CharField(max_length=100000000, blank=True) def __str__(self): return self.Post_Name.Post_Caption + " Commented By " + self.Comment_By.username I want to change the 'Comment' using AJAX but it is not changing. My AJAX view and Javascript are as follows are as follows. def EditComment(request): ctx = {} if request.method == 'POST': print(request.POST) New = Comments.objects.get(id=request.POST['Comment']) New.Comment = request.POST['Change'] New.save() print(New.Comment) ctx = {'result': 'Done'} return HttpResponse(json.dumps(ctx), content_type='application/json') And this is the script where AJAX is called. function EditComment() { var str = document.getElementById('Comment_ID').value var saveChange = document.getElementById('message-text').innerHTML console.log(str) console.log(saveChange) $.ajax( { type: 'POST', url: "{% url 'EditComment' %}", data: { 'Comment': str, 'Change': saveChange, 'csrfmiddlewaretoken': '{{ csrf_token }}' }, dataType: 'json', success: function (response) { console.log(response) }, error: function (rs) { alert(rs.responseText); } } ) } Also, in the terminal window The same comment object is printed which i want to edit...its just that the contents of it are not being edited.....I also saved the object after editing but still it doesn't save... Any Solutions??? -
Django RF, Queryset is fails to validate values in project but getting correct result in Django shell
I have a Django model, class Comment(models.Model): comment = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) During creation of above model object instance,I put a check to see if a comment object already exists, if yes it should't save. class CommentCreate(generics.CreateAPIView): .... def perform_create(self, serializer): ..... if Comment.objects.filter(Q(author=request_user.id) & Q(product__pk=pk)).exists(): return Response("You have already commented") else: # other checks The above validation is not happening,even if the user have already commented,it replaces the existing comment. I tried in Django shell below line, Comment.objects.filter(Q(author=1) & Q(product__pk=1)).exists(): It return False But in project, this line become True The complete code block for your referance class CommentCreate(generics.CreateAPIView): serializer_class = CommentSerializer queryset = Comment.objects.all() permission_classes = [IsAuthenticated] def perform_create(self, serializer): request_user = self.request.user print (request_user.id) pk = self.kwargs.get('pk') #product = Product.objects.get(pk=pk) product=get_object_or_404(Product,pk=pk) if Comment.objects.filter(Q(author=request_user.id) & Q(product__pk=pk)).exists(): return Response("You have already commented") else: try: if Po.objects.filter(Q(user=request_user) & Q(item_id=pk) & Q(delivered=True)).exists(): serializer.save(author=request_user, product=product) else: return Response("Purchase this item,prior to commenting") except: pass urls, path('CommentCreate/int:pk/', views.CommentCreate.as_view(), name='CommentCreate'), -
How to convert the datetime field in Django to be accepted by google calendar event?
I have a model contains start, end field with like this def get_deadline(): return datetime.today() + timedelta(days=0, hours=0,minutes=40) class Schedule(models.Model): start = models.DateTimeField(default=datetime.now, blank=False) end = models.DateTimeField(default=get_deadline, blank=False) When I print out is show start = 2020-07-08 17:42:00 end =2020-07-08 18:22:43.588789 How can I convert the start and end to date accepted by googel calendar event, this accepted format is look like this: date_calendar_event = 2020-07-08 10:53:32.725308+00:00 -
NoReverseMatch at / "Reverse for 'create_order' with no arguments not found. 1 pattern(s) tried: ['create_order/(?P<pk>[^/]+)/$']"
I get this error on the homepage of my website: NoReverseMatch at / Reverse for 'create_order' with no arguments not found. 1 pattern(s) tried: ['create_order/(?P[^/]+)/$'] Here is my urls.py: from django.urls import path from . import views urlpatterns = [ path('',views.home, name='home'), path('products/',views.products, name='products'), path('customer/<str:pk_test>/',views.customer, name='customer'), path('create_order/<str:pk>/', views.createOrder, name='create_order'), path('update_order/<str:pk>/', views.updateOrder, name='update_order'), path('delete_order/<str:pk>/', views.deleteOrder, name='delete_order'), ] Here is My views.py file: from django.shortcuts import render, redirect from django.urls import reverse from django.http import HttpResponse, HttpResponseRedirect from .models import * from .forms import OrderForm def home(request): orders = Order.objects.all() customers = Customer.objects.all() total_customers = customers.count() total_orders = orders.count() delivered = orders.filter(status='Delivered').count() pending = orders.filter(status='Pending').count() context = {'orders':orders, 'customers':customers, 'total_orders':total_orders, 'delivered':delivered, 'pending':pending} return render(request, 'accounts/dashboard.html', context) def products(request): products = Product.objects.all() return render(request, 'accounts/products.html', {'products':products}) def customer(request, pk_test): customer = Customer.objects.get(id=pk_test) orders = customer.order_set.all() context = {'customer':customer, 'orders':orders} return render(request, 'accounts/customer.html', context) def createOrder(request, pk): customer = Customer.objects.get(id=pk) form = OrderForm(initial={'customer':customer}) if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): form.save() return render('/') context = {'form':form} return render(request, 'accounts/order_form.html', context) def updateOrder(request, pk): order = Order.objects.get(id=pk) form = OrderForm(instance=order) if request.method == 'POST': form = OrderForm(request.POST, instance=order) if form.is_valid(): form.save() return redirect('/') context = {'form':form} return render(request, 'accounts/order_form.html', context) def deleteOrder(request, pk): … -
Django set form field value in admin unit test
I'm trying to write unit test for admin views. I've looked through Advanced testing topics and also checked Django admin tests. Yet, still I cannot figure out how I can test def save_model(self, request, obj, form, change) in my custom ModelAdmin class. This is what I have so far: def test_save_model(self): m = PurchaseVerificationAdmin(PurchaseVerification, admin.site) request = self.factory.get('/admin/PurchaseApp/purchaseverification/') request.user = self.superuser obj = PurchaseVerification.objects.create(seller = self.seller, cart = self.cart, status=Verification.UNDER_VERIFICATION) form = m.get_changelist_form(request)() form.full_clean() m.save_model(request, obj, form, None) How I can set form's field value of required model field "status"? I don't see any way of achieving that TBH. -
Create Django Form Fields with a For Loop
I have 3 models: # app/models.py class Platform(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Streamer(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Account(models.Model): name = models.CharField(max_length=50) streamer = models.ForeignKey(Platform, on_delete=models.CASCADE) platform = models.ForeignKey(Platform, on_delete=models.CASCADE) def __str__(self): return self.name In the Platform model, I have 3 objects (Instagram, Twitch, YouTube): >>> from app.models import * >>> Platform.objects.bulk_create([ ... Platform(name="Instagram"), ... Platform(name="Twitch"), ... Platform(name="YouTube"), ... ]) >>> I want to have a Streamer Creation form that: Creates a streamer object Creates an account for each platform available (all optional). So at the end I want the form to look like this: # app/forms.py class StreamerCreateForm(forms.Form): streamer = CharField(max_length=50) instagram_username = CharField(max_length=50) twitch_username = CharField(max_length=50) youtube_username = CharField(max_length=50) but without having to manually define each platform, something like: # app/forms.py class StreamerCreateForm(forms.Form): streamer = CharField(max_length=50): for platform in platforms: # somehow... platform_username = models.CharField(max_length=50) What's the best way to go about doing this? Not sure if this part is necessary to share, but this is what the view would look like: # app/forms.py class StreamerCreate(View): def get(self, request): form = StreamerForm() return render(request, 'app/streamer_create.html', {'form':form}) def post(self, request): form = StreamerForm(request.POST) if form.is_valid: # Create the streamer streamer = Streamer.objects.create(name=form.cleaned_data['streamer']) … -
Django Query, find most common value for field on a many to many relation
Given these models (where a Restaurant has many Pizzas and Pizzas have many Toppings) class Restraunt(Model) class Topping(Model): name = Charfield() class Pizza(Model): in_resteraunt = ForeignKey(Resteraunt) toppings = ManyToMany(topping, related_name='on_pizza') I'm trying to figure out how: Given a Restaurant, across all its Pizzas, what is the most common topping? One thing I came up with is something like this (where R = the restaurant) Topping.objects.filter(on_pizza__restaurant=R).annotate(the_count=Count('on_pizza')).order_by('-the_count')[0] The problem here is that I'm not sure if the on_pizza is unique to the Restaurant object, basically a topping object can be on a pizza at multiple restaurants I need it to be unique. Here I'm starting from the Topping, is there a way I could start from a queryset of pizzas? I've looked into subquery expressions but don't really see how to implement -
How can I visit django-admin backend management page on my server?
My project is one of Front-end and back-end separation. And I want to use some function from django-admin backend. And my backend project is based on nginx + uwsgi + django. I've tried to add some setting in nginx after googled but it still not work. Below is my nginx setting: server { listen 6288; server_name a-207.a-inc.cn; access_log /home/mine/work/nginx/logs/project.log; root /home/mine/code/web/dist; # my front dist file index index.html; location /static { alias /home/mine/work/project/static/; # my static file including admin template files } location ^~ /api/ { proxy_redirect off; proxy_send_timeout 1800; proxy_connect_timeout 1800; proxy_read_timeout 1800; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://python_my_project; client_max_body_size 10m; } location / { try_files $uri $uri/ / =404; } } my django-settings: STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR,'static'), ] STATIC_ROOT = os.path.join(BASE_DIR,'static') And my urls config like: urlpatterns += [ url(r'^api/', include([ url(r'^v2/', include(apipatterns)), ])), url(r'^backend/', include([ url(r'^dashboard/', admin.site.urls, name='dashboard'), ])), But I cannot visit a-207.a-inc.cn:6288/backend/dashboard to get django-admin site page. How can I make it work? Thanks. -
Save_as and Save and add another in Admin Django 3.0
I am trying to have both 'save_as' and 'save and add another' in my admin page but when i set save_as = True it overrides save and add another, but i want both. How can i do that? in my admin.py class OrderAdmin(ImportExportModelAdmin): pass save_as = False date_hierarchy = 'date_created' list_filter = ('status','date_created') list_display =('order_head', 'items', 'date_created') search_fields =('order_head__Order_Id', 'items__name', 'date_created', 'order_head__Buyer__name') admin.site.register(Order, OrderAdmin) when i do this 'save and add another' comes back but when i do the following class OrderAdmin(ImportExportModelAdmin): pass save_as = True date_hierarchy = 'date_created' list_filter = ('status','date_created') list_display =('order_head', 'items', 'date_created') search_fields =('order_head__Order_Id', 'items__name', 'date_created', 'order_head__Buyer__name') admin.site.register(Order, OrderAdmin) 'save as new' overrides 'save and add another'! Please Help, Help Appreciated. -
python with Ajax using django
This is my function but when I run this on the django server I get an error function updateUserOrder(productId, action){ console.log('User is authenticated, sending data...') var url = '/update_item/' fetch(url, { method:'POST', headers:{ 'content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId': productId, 'action': action}) }) .then((response) => { return response.json() }) .then((data) => { console.log('data', data); }) } The error say cart.js:24 POST http://127.0.0.1:8000/update_item/ 500 (Internal Server Error) uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 How do I fix this? -
How i use image in jquery in django
I Want To Use In jquery in Django with ajax in image tage means my problem in below code where wrote if(trim=='like') and else .. but i want to use image looks like if (trim=='image') and below wrote in ajax .html('liked') which place i want to use image so how i use and when i use below code for prevent default from when my count code is work after refressing so please any one tell me how i solve this issue in my views:. views.py def likePost(request): user= request.user pk=request.POST.get("post_id",'') post_obj=Post.objects.get(pk=pk) if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like,created=Like.objects.get_or_create(user=user,post_id=pk) if not created: if like.value =='Like': like.value ='Unlike' else: like.value ='Like' like.save() return redirect('user_homeview:userview') return HttpResponse("Liked") def post_serialized_view(request): data=list(Post.objects.values()) return JsonResponse(data,safe=False) in my template:. template.html <form method="POST" action="{% url 'user_homeview:like_dislike_post'%}" class="like-form" id="{{i.id}}" > {% csrf_token %} <input type="hidden" name='post_id' id='post_id' value="{{i.pk}}"> <button id="like" class="like like-btn{{ i.id }}"> {% if request.user in i.liked.all%} <img src='{% static "images\like.png" %}' class="mt-2 settin"></button> {% else %} <img src='{% static "images\unlike.jpg" %}' class=" settin"> {% endif %} </button> <strong>{{i.liked.all.count}}&nbsp;Likes</strong> </form> $(document).ready(function(){ $('.like-form').submit(function(e){ e.preventDefault(); console.log('Works done') const post_id=$(this).attr('id') console.log(this) console.log(post_id) const likeText=$(`.like-btn${post_id}`).image console.log(likeText) const trim = $.trim(likeText) console.log(trim) const url =$('.like-form').attr('action') console.log(url) $.ajax({ type: 'POST', url:url, data:{ … -
Django reset user password using sms with auth model
I have Django website that has custom user model that extends AbstractBaseUser and has the user's phone number as it's USERNAME_FIELD. The model doesn't have an Email field and the users login by their phone and a password that they have set during registration. My question is how do I implement a forgot_password feature that let users reset their password by a verification code sent by SMS ? My incomplete solution to it so far is this: create a link with a token generated by def reset_token(phone_number): # phone number taken from user code = generate_verification_code() # generate verification code that gets sent to user via api payload = { 'phone_number': phone_number, 'code': code, 'exp': datetime.utcnow() + timedelta(seconds=14400) # expires in 4 hours } encoded_data = jwt.encode(payload, 'settings.JWT_SECRET', 'HS256') return encoded_data.decode('utf-8') then send the user to the link and ask for the verification code then decode the payload if code is correct redirect to a SetPasswordForm. But, since SetPasswordForm need the user to be logged in (which is a security risk without @login_required), I dont know what to do from here. Is there a better and easier solution? Thank you. -
Upload files on Google drive using Python API without browser activity
I am working on Google Drive API to upload the video and then get the URL of that video. Here is the code I tried to upload the files: SCOPES = ['https://www.googleapis.com/auth/drive.file'] flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Now build our api object, thing drive_api = build('drive', 'v3', credentials=creds) file_metadata = { 'name': 'Test file', # 'mimeType': 'application/vnd.google-apps.spreadsheet' } media = MediaFileUpload('/path/to/file', mimetype='text/text', resumable=True) file = drive_api.files().create(body=file_metadata, media_body=media, fields='id').execute() print('File ID: %s' % file.get('id')) My end goal is to upload files on Google Drive via some scheduler on the server. I also tried tutorial to upload the files. But the above code and the tutorial always opens the browser and get permission. I want to upload files without a browser activity. How can I upload files without the browser activity like only using api_key or client_id etc? -
labeling in Django Admin
I am new to Django and still learning, I have created a database and some models but I got stuck with meaningful labels in Django Admin. This is the model: class Product(models.Model): product_id = models.AutoField(primary_key=True) product_name = models.CharField(max_length= 50) brand_name = models.CharField(max_length = 20) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) min_order = models.IntegerField() max_order = models.IntegerField() units = models.IntegerField() quantity = models.ForeignKey(Quantity, on_delete=models.SET_NULL, null=True) objects = ProductManager() class Meta: verbose_name = "Product" verbose_name_plural = 'Products' And I get this: I want Product object (3) to be replaced byt the product_name. Thank you in advance! -
Firebase OTP works the local host but in server I get this error Hostname match not found
I add the domain with www and without www to Authorized domains but we cofigure nginx according to this post http://michal.karzynski.pl/blog/2013/06/09/django-nginx-gunicorn-virtualenv-supervisor/ and I can’t know where is the problem -
Django - Sending POST request from javascript
I have a JS event-triggered function which goal is to update some objects in my database. The event which triggers the function is a drop-event, so i initially avoided using forms to pass my request, but tell me if i did wrong. So basically in my drop-event: const dragDrop = function (e) { e.preventDefault() console.log(e) const droppedElId = e.dataTransfer.getData('Text/html').split('__id-')[1] const request = new XMLHttpRequest() request.open('POST', '', true) request.setRequestHeader('Content-type', 'application/json') request.send(JSON.stringify({ 'request_name':'change-extra-fields', 'type':'increase', 'id':droppedElId, })) } I want to pass some information to my POST-view on django so i can parse the information and change whatever is needed on my object's model. However this kind of request throws an error "POST 403 (Forbidden)" and, of course, never makes it to the Django's view. I'm not sure what am i doing wrong. -
Custom transform for DateRangeField to query on delta between start and stop dates in Django
Question is regarding custom transform or lookup( can’t figure it out yet). For example I have following model. class Example(models.Model). date_range = DateRangeField() Each date_range is a object with start and stop dates, for example [2020-02-24, 2020-04-16) Question is – is it possible to create a transform or(and) lookup in order to filter instances of model by their range between start date and stop date? Example I want to find instances where difference between start and stop date would be more then 1 year. This would be something like True - [2020-02-24, 2021-04-16) - delta more then one year False - [2020-02-24, 2020-04-16) - delta less then one year Example.objects.filter(date_range__transform_name_here__gt=365) I can do it via raw SQL but I don’t want to use it as it is quite common task. Thank you. -
How to pass Django rest Framework API in Angular 9?
I purchase an angular theme, and I developed API using the Django rest framework, and I want to pass my API data in the Angular theme menu. I set up everything (like as: service, classes, components, HTML file), but I am stuck in this (how I can hit API in Angular). I am submitting my service code here, please check, and let me know how I can implement API in Menu. here are my nav.services.ts file import { Injectable, HostListener } from '@angular/core'; import { BehaviorSubject,Observable, of, from } from 'rxjs'; import { GYM } from '../classes/gym'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { environment } from '../../../environments/environment'; // Menu export interface Menu { path?: string; title?: string; type?: string; megaMenu?: boolean; image?: string; active?: boolean; badge?: boolean; badgeText?: string; children?: Menu[]; //childrens?: results[]; } @Injectable({ providedIn: 'root' }) export class NavService { // constructor() { } public screenWidth: any; public leftMenuToggle: boolean = false; public mainMenuToggle: boolean = false; // Windows width @HostListener('window:resize', ['$event']) onResize(event?) { this.screenWidth = window.innerWidth; } MENUITEMS: Menu[] = [ { title: 'home', type: 'sub', active: false, children: [ { title: 'clothing', type: 'sub', active: false, children: [ { path: '/home/fashion', title: 'fashion-01', …