coverage run -m pytest &&coverage report && coverage html

coverage report -m


 

Find the last friday using python datetime function

Posted In: . By Webdevelopmentlogics


from datetime import datetime, timedelta

def find_last_friday():     current_time = datetime.now()     last_friday = (         current_time.date()         - timedelta(days=current_time.weekday())         + timedelta(days=4, weeks=-1)     )     return last_friday


 


class GenericViewSet():     queryset = (         Contact.objects.select_related("tag")         .prefetch_related("employee")         .all()     )     serializer_class = GenericSerializer     http_method_names = ["get"]     filterset_class = GenericFilter     pagination_class = GenericPagination

def list(self, request):

        qs = self.filter_queryset(self.get_queryset())

        data = self.paginate_queryset(qs)

        serializer = self.get_serializer(qs, many=True)

        data = self.get_paginated_response(serializer.data)

        return data


 


 qs = qs.order_by(Case(

      When(status='active', then=Value(0)),

      When(status='pending', then=Value(1)), 

        default =Value(2)

    )

)


 


 # Prefetch for subsets of relationships


        queryset = queryset.prefetch_related(

            Prefetch('unaffiliated_attendees', 

                queryset=Attendee.objects.filter(organization__isnull=True))

            )


 


 class MainSerializer(serializers.ModelSerializer):

deatils= serializers.SerializerMethodField() class Meta: model = Tag fields = ["id", "name", "deatils"] def get_deatils(self, obj): if obj.user_type == "public": return PublicUserSerializer(obj.prefetch_user, many=True).data else: return AdminUserSerializer(obj.prefetch_user, many=True).data

 


 import re

txt = """The rain in 


Spain"""

x = re.search("^The.*spain$", txt, flags=re.S|re.I)


if x:

  print("YES! We have a match!")

else:

  print("No match")


 


 // Flutter code sample for BottomNavigationBar

//
// This example shows a [BottomNavigationBar] as it is used within a [Scaffold]
// widget. The [BottomNavigationBar] has four [BottomNavigationBarItem]
// widgets, which means it defaults to [BottomNavigationBarType.shifting], and
// the [currentIndex] is set to index 0. The selected item is amber in color.
// With each [BottomNavigationBarItem] widget, backgroundColor property is
// also defined, which changes the background color of [BottomNavigationBar],
// when that item is selected. The `_onItemTapped` function changes the
// selected item's index and displays a corresponding message in the center of
// the [Scaffold].

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

/// This is the main application widget.
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: _title,
      home: MyStatefulWidget(),
    );
  }
}

/// This is the stateful widget that the main application instantiates.
class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({Key? key}) : super(key: key);

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class HomepageWidget extends StatelessWidget {
  static String routeName = '/';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'App title',
      home: Container(
        child: Text('Hello World'),
      ),
    );
  }
}

/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  int _selectedIndex = 0;
  List _screens = [PageOne(), PageTwo()];
  static const TextStyle optionStyle =
      TextStyle(fontSize: 30, fontWeight: FontWeight.bold);

  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('BottomNavigationBar Sample'),
      ),
      body: _screens[_selectedIndex],
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'Home',
            backgroundColor: Colors.red,
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.business),
            label: 'Business',
            backgroundColor: Colors.green,
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.school),
            label: 'School',
            backgroundColor: Colors.purple,
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.settings),
            label: 'Settings',
            backgroundColor: Colors.pink,
          ),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.amber[800],
        onTap: _onItemTapped,
      ),
    );
  }
}

class PageOne extends StatelessWidget {
  final SnackBar _snackBar = SnackBar(
    content: const Text('Message from page one'),
    duration: const Duration(seconds: 5),
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.teal,
        title: Text('Woolha.com - Page one'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            OutlinedButton(
              child: Text('Go to page two'),
              onPressed: () {
                Navigator.pushNamed(context, '/two');
              },
            ),
            OutlinedButton(
              child: Text('Show message!'),
              onPressed: () {
                ScaffoldMessenger.of(context).showSnackBar(_snackBar);
              },
            ),
          ],
        ),
      ),
    );
  }
}

class PageTwo extends StatelessWidget {
  final SnackBar _snackBar = SnackBar(
    content: const Text('Message from page two'),
    duration: const Duration(seconds: 5),
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.teal,
        title: Text('Woolha.com - Page Two'),
      ),
      body: Builder(builder: (BuildContext context) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              OutlinedButton(
                child: Text('Go to page one'),
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
              OutlinedButton(
                child: Text('Show message!'),
                onPressed: () {
                  ScaffoldMessenger.of(context).showSnackBar(_snackBar);
                },
              ),
            ],
          ),
        );
      }),
    );
  }
}


 


 class BaseViewSet(BaseModelViewSet):

    queryset = model.objects.all()

    serializer_class = modelSerializer

    http_method_names = ["get"]

    filterset_class = modelFilter


    def get_serializer_class(self):

        year = self.request.GET.get("year")

        if year:

            return yearSerializer

        return modelSerializer


 


To install python with specific version in virtualenv use the following command
virtualenv --python=/usr/bin/python3.2 MyEnv

 

Using multiple model in django form

Posted In: , . By CreativeSolutions


 To use profile model with user form we need to initialize the form fields in the form. Then to get the values on edit we need to initialize __init__ function and passing the profile object from the view

 Ex: forms.py
 class SuperUserEditForm(forms.ModelForm):
    birthday = forms.DateTimeField(input_formats=['%Y-%m-%d %I:%M %p'], required=False)
    phone_number = forms.CharField(max_length=100, required=False, label="Home Phone")
    cell_number = forms.CharField(max_length=100, required=False)
    carrier = forms.ChoiceField(choices=CARRIERS, required=False)
   
    def __init__(self, profile=None, *args, **kwargs):
        super(SuperUserEditForm, self).__init__(*args, **kwargs)
        if(profile):
            self.fields['cell_number'].initial = profile.cell_number
            self.fields['carrier'].initial = profile.carrier
            self.fields['birthday'].initial = profile.birthday
            self.fields['phone_number'].initial = profile.phone_number

 Ex: views.py
     form = SuperUserEditForm(profile=profile, instance=user)

     on POST
     form = SuperUserEditForm(data=request.POST, instance=user)

 

How to remove a category from top menu

Posted In: . By CreativeSolutions


1. Login to Admin
2. From the left menu Product > Categories  > [Select a category] > General Information (tab) > Include in Navigation Menu
3. Change it value to No

 

How to enable developer mode in magento

Posted In: . By CreativeSolutions


To check the current mode, go to the magento installed folder using terminal then use the below command bin/magento deploy:mode:show

[developer@user magento]$ bin/magento deploy:mode:show
Current application mode: default.

To change into developer mode, use the below command

[developer@user magento]$ bin/magento deploy:mode:set developer
Enabled developer mode.
[developer@user magento]$ bin/magento deploy:mode:show
Current application mode: developer.


 

Removing My Wishlist option in Magento

Posted In: . By CreativeSolutions


1. Login to Admin Panel
2. Go to Stores > Configuration > Customers > Wish list > General Options
3. Change Enabled field value to Yes/No

 


1. Login into Admin Panel
2. Take the attribute listing from Store=>Attribute=>Product, then edit the attribute
3. On Edit page there is a tab Storefront Properties and in that make the Visible on Catalog Pages         on Front value to Yes

 


To change all the directory permission in the path /var/www/html/ use the below command
 find /var/www/html/ -type d -exec chmod 755 {} \;
and for files
 find /var/www/html/ -type f -exec chmod 644 {} \;

 


In the linux machine go to the folder /tmp/magento/var/cache
then type the command $ rm -rf *

Then press Ctrl+F5 in the browser

 

Csv upload and import in python django

Posted In: , . By CreativeSolutions


 if request.method == 'POST':
        srcfile = request.FILES.get("file", None)
        reader = csv.DictReader(srcfile) # read rows into a dictionary format
        for row in reader:
   print row

 

How to show django cursor execute query

Posted In: . By CreativeSolutions


 We can use the variable _executed with the cursor object ie. cursor._executed

 cursor = connection.cursor()
 cursor.execute(sql, (params))
 print cursor._executed
 rows = cursor.fetchall()

 

Using for loop counter in django template

Posted In: . By CreativeSolutions


 Django has the function forloop.counter to use the index for the row in template

 Ex:
 {% for question in questions %}
{{ forloop.counter }}
  {% endfor %}